1. Two Sum

来源:互联网 发布:变女声软件 编辑:程序博客网 时间:2024/05/15 11:38

第一道LeetCode题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

第一直觉二重循环,我的代码如下:

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

时间复杂度:O(N2)
空间复杂度:O(1)
这个应该是最轻易能想到的解法


参看答案后发现另两种解法:利用Hash Table,将搜寻第二个匹配解的时间复杂度从O(N)降低到O(1)

解法一:
A simple implementation uses two iterations. In the first iteration, we add each element’s value and its index to the table. Then, in the second iteration we check if each element’s complement (target - nums[i]target−nums[i]) exists in the table. Beware that the complement must not be nums[i]nums[i] itself!

public int[] twoSum(int[] nums, int target) {    Map<Integer, Integer> map = new HashMap<>();    for (int i = 0; i < nums.length; i++) {        map.put(nums[i], i);    }    for (int i = 0; i < nums.length; i++) {        int complement = target - nums[i];        if (map.containsKey(complement) && map.get(complement) != i) {            return new int[] { i, map.get(complement) };        }    }    throw new IllegalArgumentException("No two sum solution");}

时间复杂度:O(N)
空间复杂度:O(N)

解法二:
It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element’s complement already exists in the table. If it exists, we have found a solution and return immediately.

public int[] twoSum(int[] nums, int target) {    Map<Integer, Integer> map = new HashMap<>();    for (int i = 0; i < nums.length; i++) {        int complement = target - nums[i];        if (map.containsKey(complement)) {            return new int[] { map.get(complement), i };        }        map.put(nums[i], i);    }    throw new IllegalArgumentException("No two sum solution");}

时间复杂度:O(N)
空间复杂度:O(N)