給定整數陣列和一個目標資料,返回陣列中的兩數之和是目標資料的陣列下標-leetcode

2020-10-28 18:06:04
package com.pshdhx.easy;

import java.util.HashMap;
import java.util.Map;

/**
 * twoSum
 * @author pshdhx
 * 給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
 *
 */
public class TwoSum {
	/**
	 * 暴力列舉法
	 * @param nums
	 * @param target
	 * @return
	 */
	public int[] twoSum(int[] nums, int target) {
		int res[] =new int[2];
		for(int i=0;i<nums.length;i++) {
			for(int j=i+1;j<nums.length;j++) {
				if(nums[i]+nums[j]==target) {
					res[0] = i;
					res[1] = j;
				}
			}
		}
		return res;
    }
	/**
	 * 雜湊法
	 * @param nums
	 * @param target
	 * @return
	 * 靈感:加法變減法=>兩次迴圈遍歷用雜湊表的containsKey,陣列在前,i在後;
	 */
	public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
            	System.out.println(hashtable.get(target - nums[i])+"-----1");
            	System.out.println(i+"-----2");
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i); // (2,0) (//進入判斷了)
            System.out.println(hashtable.toString());
        }
        return new int[0];
    }
	public static void main(String[] args) {
		
		  int a[]= {2, 7, 11, 15}; 
		  int[] twoSum = new TwoSum().twoSum(a, 9); 
		  for(int i=0;i<twoSum.length;i++) { 
			  System.out.println(twoSum[i]);
		  }
		 
		//int[] twoSum2 = new TwoSum().twoSum2(new int[] {2, 7, 11, 15}, 9);
	}
}

 

用空間換時間的做法:用雜湊法減少一次遍歷。