-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1. Two Sum
47 lines (40 loc) · 1016 Bytes
/
1. Two Sum
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
//in O(nlogn)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n=nums.size();
vector< pair<int, int>>p;
for(int i=0; i<n; i++)
{
p.push_back(make_pair(nums[i],i));
}
sort(p.begin(), p.end());
int i=0, j=n-1;
while(i<j)
{
if((p[i].first + p[j].first)==target)
return {p[i].second, p[j].second};
else if((p[i].first + p[j].first)<target)
i++;
else
j--;
}
return {};
}
};
//in O(n^2)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i=0;i<nums.size();i++)
//For first element....
{
for(int j=i+1;j<nums.size();j++)
{ //and second....
if((nums[i]+nums[j])==target){
return {i,j}; }
}
}
return {};
}
};