1. 程式人生 > >LeetCode 1. 兩數之和

LeetCode 1. 兩數之和

題目描述:

給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。

你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1] 

暴力解法:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for(int i = 0;i<nums.length-1;i++){
            for(int j =i+1;j<nums.length;j++){
                if(nums[i] + nums[j]==target){
                    res[0] = i;
                    res[1] = j;
                }
            }
        }
        return res;
    }
}

HashMap: 

/*
Class HashMap<K,V>

Type Parameters:
K - the type of keys maintained by this map
V - the type of mapped values

V-get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

V-put(K key, V value)
Associates the specified value with the specified key in this map.


*/
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        Map map = new HashMap();
        for(int i = 0; i < nums.length; i++){
            map.put(numbers[i], i);
        }
        for(int i = 0; i < nums.length; i++){
            int gap = target - nums[i];
            if(map.get(gap)!= null && (int)map.get(gap)!= i){
                res[0] = i;
                res[1] = (int)map.get(gap);
                break;
            }
        }
        return res;
    }
}