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
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> ans;
map<int, int> m;
for(int i=0; i<numbers.size(); i++)
{
if(m.count(target - numbers[i]))
{
ans.push_back(m[target-numbers[i]] + 1);
ans.push_back(i + 1);
return ans;
}
if(!m.count(numbers[i]))
m[numbers[i]] = i;
}
return ans;
}
};
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num)
{
vector<vector<int> > ans;
sort(num.begin(), num.end());
for(int i=0; i<num.size(); i++)
{
if(num[i] > 0)
break;
if(i > 0 && num[i] == num[i-1])
continue;
int l = i+1;
int r = num.size() - 1;
int target = -num[i];
while(l < r)
{
if(num[l] + num[r] == target)
{
vector<int> v({num[i], num[l], num[r]});
ans.push_back(v);
while(l < r && num[l] == num[l+1])
++l;
while(l < r && num[r] == num[r-1])
--r;
++l;
--r;
}
else if(num[l] + num[r] < target)
++l;
else
--r;
}
}
return ans;
}
};
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
set<vector<int> > ans;
sort(num.begin(), num.end());
for(int i=0; i<num.size(); ++i)
{
for(int j=i+1; j<num.size(); ++j)
{
int l = j+1;
int r = num.size() - 1;
while(l < r)
{
int sum = num[i] + num[j] + num[l] + num[r];
if(sum == target)
{
vector<int> v;
v.push_back(num[i]);
v.push_back(num[j]);
v.push_back(num[l]);
v.push_back(num[r]);
ans.insert(v);
++l;
--r;
}
else if(sum < target)
++l;
else
--r;
}
}
}
return vector<vector<int> > (ans.begin(), ans.end());
}
};