LeetCode #001 Two Sum
原题链接:https://leetcode.com/problems/two-sum/
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
解题思路
原始思路:遍历数组,取target与每次遍历的值作差,在数组中剩余的值里寻找差值。
代码原始思路:嵌套循环遍历数组,查看两次遍历的数值和是否和target相等,时间复杂度O(N^2)
注意点:因为在内外层循环中同一个数只能使用一次,所以要保证内外层循环使用的数值不同。
改进思路: 这里我使用下标间隔internal来实现。
通过计算nums[i]+nums[i+internal],来求和。外层循环使用internal递增(有点类似希尔排序或者分治法的思想)。
如nums中有10个数,下标1,2,3....10
外循环第一次作和:[0]+[1],[1]+[2],[2]+[3],[3]+[4],...,[8]+[9]
第二次作和:[0]+[2],[1]+[3],[2]+[4],[3]+[5].....[7]+[9]
............
第10次作和:[0]+[9]
具体代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int internal = 1;
for (internal = 1; internal <nums.size(); internal++) {
for (int j = 0; j < (nums.size()-internal);j++){
if ((nums[j+internal] + nums[j]) == target) {
vector<int> result = {j,j+internal};
return result;
}
}
}
}
};
不过有一点疏漏的是,没有考虑到如果存在大量冗余数据的话,会重复遍历和输出相同的组合,具体讨论见 LeetCode #015 3Sum