Leetcode:两数之和

1.暴力搜索

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

2.两遍哈希表

class Solution {
    public int[] twoSum(int[] nums, int target) {
       HashMap map = new HashMap();
       for (int i = 0; i < nums.length; i ++) {
           map.put(nums[i],i);
       }
       for(int j = 0; j < nums.length; j ++) {
           int complement = target - nums[j];
           if(map.containsKey(complement) && map.get(complement) != j) {
               return new int[] {j,map.get(complement)};
           }
       }
       throw new IllegalArgumentException("No two sum solution");
    }
}

3.一遍哈希表

class Solution {
    public int[] twoSum(int[] nums, int target) {
       HashMap map = new HashMap();
       for(int j = 0; j < nums.length; j ++) {
           int complement = target - nums[j];
           if(map.containsKey(complement)) {
               return new int[] {j,map.get(complement)};
           }
           map.put(nums[j],j);
       }
       throw new IllegalArgumentException("No two sum solution");
    }
}

 

你可能感兴趣的:(Leetcode,Leetcode)