LeetCode Two Sum

来源:互联网 发布:源码时代教育怎么样 编辑:程序博客网 时间:2024/05/24 03:02

Two Sum

 

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        int i = 0, j = numbers.size() - 1;        vector<int> num(numbers);        vector<int> r;        sort(num.begin(),num.end());        while(i < j) {            if(num[i]+num[j] == target) break;            else if(num[i]+num[j] < target) i++;            else j--;        }        for(int k = 0; k < numbers.size(); k++) {            if(numbers[k] == num[i] || numbers[k] == num[j]) r.push_back(k+1);        }        return r;    }};

思路:解法时间复杂度O(nlogn),首尾指针向中间逼近,直到遇到两数和为target,下面证明这种方法。

设num中,满足num[m] + num[n] = target。

(1).首先考虑算法开始时, i = m, j = n 的情况,显然算法正确。

(2).首先考虑算法开始时, i = m, j ≠ n 或 i ≠ m, j = n的情况,显然算法接下来将要执行的是:i 或 j 其中一个不动,另一个不断向中间移动,最后到达 i = m, j = n。

(3).然后考虑算法开始时,≠ m, j ≠ n 即 i < m, j > n 的情况。若 num[i]+num[j] < target ,因为数组是有序的,所以可以推出 num[i] + num[k] < target (i<k<=j),也就是说num[i]与所有其他数都无法成功加和到target,所以可以淘汰;num[i]+num[j] > target 同理。这一步之后的 i, j 虽然移动了,但实际上可以看成还是在一个数组的首尾两端, i 前面的元素或 j 后面的元素已经被淘汰。因此这一步可以看成又回到了算法的开始,情况为(1)或(2)或(3)。而因为正确答案肯定存在,所以最后必将回到(1)或(2)。因此,算法正确。

暴力解法时间复杂度O(n^2),因为超时无法通过。

附:暴力解法

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int> r(2,0);        for(int i = 0; i < numbers.size(); i++) {            for(int j = i + 1; j < numbers.size(); j++) {                if(numbers[i]+numbers[j]==target) {                    r[0] = i + 1;                    r[1] = j + 1;                    return r;                }            }        }    }};


0 0