[LeetCode] #1 两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

输入:nums = [2,7,11,15], target = 9

输出:[0,1]

暴力解法

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

进阶

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0;i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[] {map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[] {-1, -1};
    }
}

知识点:map中的containsKey(key)方法是判断该key在map中是否有key存在。如果存在则返回true。如果不存在则返回false。

总结:当需要重复遍历一个数组(或是链表等等),可以考虑在遍历过程中(使用哈希表)记录,从而减少遍历次数。

posted @ 2021-07-14 16:43  1243741754  阅读(25)  评论(0编辑  收藏  举报