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
解决方案1:排序完从两端开始夹逼,时间复杂度O(nlogn)。排序O(nlogn), 查找O(n).但是结果必须输出index,所以此方案不成立
解决方案2:穷举遍历,时间复杂度O(n2)
解决方案3:用哈希表存储,然后遍历
因为unordered_map的查找时间复杂度为O(logn),所以此算法时间复杂度为O(nlogn)
//解决方案3
class Solution {
public:
vector<int> twoSum(vector<int>& num, int target) {
unordered_map <int, int> mapping;
vector <int> result;
for (int i = 0; i < num.size(); ++i) {
mapping[num[i]] = i;
}
for (int i = 0; i < num.size(); ++i) {
const int cmp = target - num[i];
//find(key)
//如果mapping.find() == mapping.end() 则说明未找到
if (mapping.find(cmp) != mapping.end() && mapping[cmp] > i) {
result.push_back(i + 1);
result.push_back(mapping[cmp] + 1);
break;
}
}
return result;
}
};
解决方案4:假设输入的值范围在-/+ 40000,可以用如下方法解决
以空间换时间的方式。时间复杂度O(n)
//解决方案4
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int>ans;
int tmp[80000]={0};
for(int i=0;i<nums.size();i++)
tmp[40000+nums[i]]=i+1;
for(int i=0;i<nums.size();i++)
if(tmp[40000+target-nums[i]]&&tmp[40000+target-nums[i]]!=i+1)
{
ans.push_back(i+1);
ans.push_back(tmp[40000+target-nums[i]]);
return ans;
}
}
};
解决方案4属于投机取巧的方法,不过在我之前面试时碰到的一个题目是给定范围让你排序或者查找个数,其实也可以利用到解决方案4的方法。
引用:
https://github.com/soulmachine/leetcode
https://leetcode.com/discuss/57223/my-code-beats-99%25-8ms-using-c