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.
I have tried to use map in c++, however, it finds 542-863=-321 in dict, so strange.
#include <iostream>
#include <map>
#include <vector>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
int len=nums.size();
if(len==0){
return result;
}
map<int, int> dict;
map<int, int>::iterator iter;
for(int i=0; i<len;i++){
dict[nums[i]]=i;
int ss=target-nums[i];
cout<<ss<<" ";
int tag=dict.count(ss);
cout<<tag<<"tag"<<endl;
if(dict[target-nums[i]]!=i && tag!=0){
result.push_back(i);
result.push_back(dict[target-nums[i]]);
break;
}
}
cout<<result[0]<<result[1]<<endl;
return result;
}
int main(){
int a[]={230,863,916,585,981,404,316,785,88,12,70,435,384,778,887,755,740,337,86,92,325,422,815,650,920,125,277,336,221,847,168,23,677,61,400,136,874,363,394,199,863,997,794,587,124,321,212,957,764,173,314,422,927,783,930,282,306,506,44,926,691,568,68,730,933,737,531,180,414,751,28,546,60,371,493,370,527,387,43,541,13,457,328,227,652,365,430,803,59,858,538,427,583,368,375,173,809,896,370,789};
cout<<sizeof(a)/sizeof(a[0])<<endl;
vector<int> nums(a, a+100);
twoSum(nums, 542);
}
output [40,0]
expect [28,45]
Aucun commentaire:
Enregistrer un commentaire