每日一练之Two sum [leetcode No.1]
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].
题意:一个数组中任意两个位置上的数之和为target,求这两个位置。分析:暴力求解法的时间复杂度为O(n^2),会TLE(Time Limit Exceeded)。所以可以先排序,然后用双指针向中间夹逼,复杂度O(nlogn)。
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int sz = numbers.size();
int left = 0, right = sz - 1, sum = 0;
vector<int> sorted (numbers);
std::sort(sorted.begin(), sorted.end());
vector<int> index;
while (left < right) {
sum = sorted[left] + sorted[right];
if (sum == target) {
// find the answer
for (int i = 0; i < sz; i++) {
if (numbers[i] == sorted[left])
index.push_back(i );
else if (numbers[i] == sorted[right])
index.push_back(i );
if (index.size() == 2)
return index;
}
} else if (sum > target) {
right--;
} else {
left++;
}
}
// Program never go here, because
// "each input would have exactly one solution"
}
};
还有两种思路是:
1. 可以用 Map 记录出现的数,只要判断有没有和当前的数凑成 target 的数,再找出来就行,复杂度 O(nlogn) 而不是 O(n) ,因为 Map 也要复杂度的。
2. 在 2 中的 Map 复杂度可以用数组来弥补,时间复杂度是 O(n) ,不过空间复杂度是 O(MAXN)。
参考文献:https://github.com/illuz/leetcode