leetcode简单难度【两数之和】

286 阅读1分钟

记录新手单刷 leetcode 的过程,以此督促自己,写的不好的地方请各位大佬多多指点.

两数之和

1. 最无脑的解法. (for循环遍历)

跟官方的的暴力法思路一致

时间复杂度O(n)²

空间复杂度O(1)

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 (target ==  nums[i] + nums[j]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

2. 利用 hash 优化 (这里我没想到,这里用了官方的方法进行优化)

我们用 hashMap 建立下标与数字的索引。

    // 利用空间换取速度
    // 在这里我们使用 HashMap 建立索引关系
    // 还可以算下初始用量,提升下效率 int initialCapacity = (int) ((float) length / 0.75F + 1.0F);
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }

接下来我们使用迭代的方式去hash表中查找我们想要的数据。

for (int i = 0; i < nums.length; i++) {
    // complement 就是我们要找的另一个数字
    int complement = target - nums[i];
    // map.get(complement) != i 是因为题目中含有条件 `你不能重复利用这个数组中同样的元素。`
    if (map.containsKey(complement) && map.get(complement) != i) {
        // 如果找到了,则表示匹配上了。
        return new int[] { i, map.get(complement) };
    }
}

时间复杂度 O(n) 因为hashMap遍历的时间复杂度是O(1),当然排除hash冲突这种情况。 空间复杂度 O(n) 我们将数据存到 hashMap 中。

PS:leetcode 官方还有种方法,在往 hashMap 中存值的时候顺便做判断,如果有则返回。时间复杂度与空间复杂度与上述方法相同,感兴趣的可以自己尝试下。