Coder's Cat

LeetCode: 3Sum

2019-10-15

Solution for LeetCode 3sum

Question

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:

[
[-1, 0, 1],
[-1, -1, 2]
]

Explaination

For time optimization, we need to sort the given array. Then enumerate the elements from index 0(assume value v0), try to find the 2 elements which some sum of them is -v0.

Time complexity is: $$ O(N^2) $$

Code

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());

if(nums.size() < 3) return ans;
for(int i=0; i < nums.size(); i++) {
int l = i+1, r = nums.size() - 1;
int v = -nums[i];
while(l < r) {
int s = nums[l] + nums[r];
if (s == v) {
vector<int> e {nums[i], nums[l], nums[r]};
ans.push_back(e);
l++, r--;

//skip same elements
while(l < r && nums[l] == nums[l-1]) l++;
while(l < r && nums[r+1] == nums[r]) r--;
}
else if(s > v) r--;
else l++;
}
while(i+1 < nums.size() && nums[i+1] == nums[i])
i++;
}
return ans;
}
};

Join my Email List for more insights, It's Free!😋