Problem:
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].
解题思路
解题很容易,就是找到两个数组中两个数相加等于目标值所在的位置
解题1
暴力查找,最简单思路,双重循环,对每一个数进行循环算和,直到找到两个值之和结果等于目标值
时间复杂度:O(n^2)
运行时间:159ms处于中等水平
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int size=nums.size();
vector<int>result;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(nums[i]+nums[j]==target)
{
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return result;
}
};
解题2:
哈希查找,将数值按照 < value,index>的规则放入map中,在放入map前查找当前map中是否已存在数值使得两值相加等于目标值,找到则返回
另外参考其他代码使用无序map, unordered_map
,关闭输入输出流绑定std::ios::sync_with_stdio(false);cin.tie(NULL);
时间复杂度:O(N)
运行时间:4ms,目前时间最短,超过100%对手
static auto x = [](){
// turn off sync
std::ios::sync_with_stdio(false);
// untie in/out streams
cin.tie(NULL);
return 0;
}();
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>mapNums;
vector<int>result;
int size=nums.size();
for(int i=0;i<size;i++)
{
if(mapNums.find(target-nums[i])!=mapNums.end()){
result.push_back(mapNums[target-nums[i]]);
result.push_back(i);
return result;
}
mapNums[nums[i]]=i;
}
return result;
}
};
最快样例代码:
将数值按照 < value,index>的规则放入map中,全部放入后对map内元素按照value值进行排序,从头和尾相向查找计算,若计算小于目标,则头部下标后移,若大于目标,则尾部下标前移。
个人认为这种效率并不一定会更好,因为需要对数据进行排序,当数据量大的时候,排序的时间复杂度会是一大瓶颈
时间复杂度:O(N)
运行时间:4ms
static auto x = [](){
// turn off sync
std::ios::sync_with_stdio(false);
// untie in/out streams
cin.tie(NULL);
return 0;
}();
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> indices;
int lenOfVectors = nums.size();
bool found=false;
vector< pair<int, int> > new_nums;
for(int i=0; i<lenOfVectors; ++i){
new_nums.push_back(make_pair(nums[i], i));
}
sort(new_nums.begin(), new_nums.end());
int j=0, k=lenOfVectors-1;
while(j<k){
if(new_nums[j].first+new_nums[k].first==target){
indices.push_back(new_nums[j].second);
indices.push_back(new_nums[k].second);
break;
}
else if(new_nums[j].first+new_nums[k].first<target){
j++;
}
else{
k--;
}
}
return indices;
}
};