-
Notifications
You must be signed in to change notification settings - Fork 0
/
1_Two Sum.txt
78 lines (68 loc) · 2.31 KB
/
1_Two Sum.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/********************************************************************************************************
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].
********************************************************************************************************/
//新的思路,果然还是有进步的
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result(2,0);
map<int,int> save;
for(int i = 0; i < nums.size(); i++){
int tmp = target - nums[i];
if(save.find(tmp) != save.end()){
result[0] = save[tmp];
result[1] = i;
return result;
}else{
save[nums[i]] = i;
}
}
return result;
}
};
//很久之前的代码,用的居然是暴力破解
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> num1,re;
int x,y;
num1.assign(nums.begin(),nums.end());
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-1;i++)
{
for(int j=nums.size()-1;j>i;j--)
{
if(nums.at(i)+nums.at(j)==target)
{
x=nums.at(i);
y=nums.at(j);
int m=0;
for(vector<int>::iterator it=num1.begin();(it<num1.end())&&(re.size()<2);it++,m++)
{
if(*it==x)
{
re.push_back(m);
continue;
}
else if(*it==y)
{
re.push_back(m);
continue;
}
}
return re;
}
else if(nums.at(i)+nums.at(j)<target)
{
break;
}
}
}
return re;
}
};