Leetcode【1】Two Sum(Java版)

暴力法:

所有人都要一遍过啊

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

两遍哈希表

这个说实话你见过,用多了也就熟练了

两个数的和等于一个数,我们遍历数组,每次拿到这个数,然后和目标值做个减法,看下差在数组的其他位置存在不

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

这里的containsKey返回true或false,告诉我们差值(key)是否存在于数组

发布了217 篇原创文章 · 获赞 78 · 访问量 152万+

猜你喜欢

转载自blog.csdn.net/ssjdoudou/article/details/104089726