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: 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] ]
唔,虽说N sum都是套路了,然额很早就写了two sum,当时数组是乱序所以拿map写的,到了3 sum就还是有点懵,感觉那个办法没法用了。其实还是可以用,只不过初始化的位置不同罢了。
然额,然额,为喵评论区的写法永远更优雅QAQ
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> > ans;
if (nums.empty()) return ans;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i) {
if (i == 0 || nums[i] != nums[i-1]) {
int le = i + 1, ri = nums.size() - 1;
int sum = 0 - nums[i];
while (le < ri) {
if (nums[le] + nums[ri] == sum) {
vector<int> loc;
loc.push_back(nums[i]);
loc.push_back(nums[le]);
loc.push_back(nums[ri]);
ans.push_back(loc);
le++;
while (le < ri && nums[le] == nums[le-1]) le++;
ri--;
while (le < ri && nums[ri] == nums[ri+1]) ri--;
}
else if (nums[le] + nums[ri] < sum) le++;
else ri--;
}
}
}
return ans;
}
};
167. Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
int le = 0, ri = nums.size() - 1;
while (le < ri) {
if (nums[le] + nums[ri] == target) {
ans.push_back(le+1);
ans.push_back(ri+1);
break;
}
else if (nums[le] + nums[ri] < target) le++;
else ri--;
}
return ans;
}
};