0
点赞
收藏
分享

微信扫一扫

每日n刷:leetcode1. 两数之和

小迁不秃头 2022-01-25 阅读 73

1. 两数之和

https://fishi.top/fishpic/f21763b7-2e34-40dc-9595-aca3fd0d5601.png

hash表

暴力解法O(n2)

需要注意,暴力的起始点两个数不能从同一个位置开始暴力。

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

hash表存储O(n)

每次查找hash表中是否有匹配的数据,如果没有那么把需要匹配的值放入hash表中。

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

相关推荐

0 条评论