Skip to content

传送门:https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked

题意就是让我们找到两个和为target的数的下标。

第一眼思路我们可以暴力枚举两个数然后判断条件,时间复杂度为O(n2)

然后我们不难想到可以用hash表来做,用原数组的值作为hash表的键,下标作为hash表的值,这样假设第一个数为ai,那么第二个数的下标就为:map[targetai],就得到了两个下标,并且hash表的查询和添加时间复杂度均为O(1),故总时间复杂度为O(n)

参考代码:

java
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> num = new HashMap<>();
        for(int i = 0;i < nums.length;i++) {
            num.put(nums[i], i);
        }
        for(int i = 0;i < nums.length;i++) {
            int other_num = target - nums[i];
            if(num.get(other_num) != null && i != num.get(other_num)) {
                return new int[]{i, num.get(other_num)};
            }
        }
        return null;
    }
}

Hash表推荐文章:https://www.hello-algo.com/chapter_hashing/hash_map/