2 Sum

2017-08-16  本文已影响0人  Herbert_Ti
题目

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.

给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。你需要实现的函数two Sum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0 开头。

https://leetcode.com/problems/two-sum/description/
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/

样例

如果有一个数组 nums = [2, 7, 11, 15], target = 9,
因为 nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解题思路

针对2 Sum这道题,我们一般考虑三种方式。
第一种是暴力搜索,两个for循环之后,来求得结果,但是要注意的是,时间复杂度是比较高的,为O(n^2);
具体代码:

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;
}

第二种方式是用Two Pointers 两个指针的方式,来前后双指针遍历,注意这种方式的时间复杂度其实是O(n)的,因为前后指针加起来只遍历一次。

public int[] twoSum(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int[] res = new int[2];
        while (left < right) {
            if (nums[left] + nums[right] == target) {
                // 因为下标从1开始,而不是从0开始,所以要加1
                res[0] = left + 1; 
                res[1] = right + 1;
                break;
            } else if (nums[left] + nums[right] < target) {
                left++;
            } else {
                right--;
            }
        }
        return ans;
}

第三种方式呢,是用HashMap方法来解决,此时时间复杂度为O(n)。具体的解决方式是这样:
比如说 我们有 [2, 7, 11, 15] 这个数组,我们假设A + B 是等于 target的;那么此时就有 B = target - A。
我们向HashMap中的Key和Value分别存的是nums[i]和下标i,那么此时就有 [2, 7, 11, 15] 一一对应 [0, 1, 2, 3]。
那么此时我们对数组遍历一次,当我们的Key中包含B时,Value对应的就是B此时的下角标;而此时我们index对应的就是A的下角标。
具体代码如下:

public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] res = new int[2];
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
            }
            map.put(nums[i], i);
        }
        return res;
}
上一篇下一篇

猜你喜欢

热点阅读