1. 程式人生 > >Java-LeetCode-TwoSum

Java-LeetCode-TwoSum

Given an array of integers, return indices ofthe two numbers such that they add up to a specific target.

You may assume that each input wouldhave exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2+ 7 = 9,

return [01].

給出一個數組nums[],然後找出其中兩個數的和為target的數的下標。這裡給出兩種解法,(1)利用暴力演算法求解,兩次變數,時間複雜度為O(n^2)級別。(2)利用雜湊來解決,其中,用陣列的值作為鍵存入雜湊表中,陣列的下標作為值存入雜湊表中。

解法一:

public class Solution {
	public int[] twoSum(int[] nums, int target) {
	    for(int i = 0; i < nums.length - 1; i++){
	         for(int j = i + 1; j < nums.length; j++){
	             if(nums[i] + nums[j] == target){
	                return new int[]{i, j};
	            }
	        }
	    }
	    throw new IllegalArgumentException("No two sum solution");
	}
}
解法二:
public class Solution{
    //該過程先判斷陣列的值是否在HashMap的鍵中,如果不在HashMap中,則將target和nums的差以鍵存入HashMap中,同時將nums在陣列中的下標存入HashMap的值中。如果HashMap的鍵中包含陣列中的值,則將HashMap的值和陣列的下標輸出。
    public int[] twoSum(int[] nums, int target){
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] result = new int[2];
        
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                int j = map.get(nums[i]);
                result[0] = j;
                result[1] = i;
                break;
            }else{
                map.put(target - nums[i], i);
            }
        }
        return result;
    }
}