shanX
文章31
标签17
分类9
Leetcode-001-两数之和

Leetcode-001-两数之和

Leetcode-001-两数之和

目前两种方法

暴力枚举:

class Solution {
    public int[] twoSum(int[] nums, int target) {
       int[] res = new int[2];
        int a;
        int b = 0;

        for (int i = 0; i < nums.length; i++) {
            a = nums[i];
            for (int j = i+1; j < nums.length; j++) {
                b = a + nums[j];
                if (b == target) {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }

        return res;
}
}

HashMap 法:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        //将nums用例放入hashmap
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            hashMap.put(nums[i],i);
        }

        for (int i = 0; i < nums.length; i++) {
            // 直接找另一个数是否存在,第二个条件防止用例中出现重复数字的时候找到自己,导致结果出错
            if (hashMap.containsKey(target-nums[i]) && hashMap.get(target-nums[i])!=i){
                res[0] = i;
                res[1] = hashMap.get(target-nums[i]);
                break;
            }
        }
        return res;
}
}

问题:hashmap.contains 方法是否扫全部内容?

本文作者:shanX
本文链接:https://rhymexmove.github.io/2021/04/18/38a5f92b31f2/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可