Skip to content

Commit 1c6f5c8

Browse files
committed
Added : 3 Sum
1 parent 94ee512 commit 1c6f5c8

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
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.
2+
3+
Note:
4+
5+
The solution set must not contain duplicate triplets.
6+
7+
Example:
8+
9+
Given array nums = [-1, 0, 1, 2, -1, -4],
10+
11+
A solution set is:
12+
[
13+
[-1, 0, 1],
14+
[-1, -1, 2]
15+
]
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
@lc id : 15
3+
@problem : 3 Sum
4+
@author : rohit
5+
@url : https://leetcode.com/problems/3sum/
6+
@difficulty : medium
7+
*/
8+
9+
class Solution {
10+
11+
public void twoSums(int[] nums, int requiredSum, int first, List<List<Integer>> result){
12+
13+
int second = nums.length - 1;
14+
15+
while(first < second){
16+
17+
int currSum = nums[first] + nums[second];
18+
19+
if(currSum == requiredSum){
20+
result.add(Arrays.asList(-requiredSum, nums[first], nums[second]));
21+
first++;
22+
second--;
23+
24+
while(nums[first] == nums[first-1] && first < second)
25+
first++;
26+
27+
while(nums[second] == nums[second+1] && second > first)
28+
second--;
29+
}
30+
31+
else if(currSum > requiredSum) second--;
32+
else first++;
33+
34+
}
35+
}
36+
37+
38+
public List<List<Integer>> threeSum(int[] nums) {
39+
List<List<Integer>> result = new ArrayList<>();
40+
Arrays.sort(nums);
41+
42+
for(int i = 0; i < nums.length - 2; i++){
43+
if(i > 0 && nums[i] == nums[i-1])
44+
continue;
45+
twoSums(nums, -nums[i], i+1, result);
46+
}
47+
48+
return result;
49+
50+
}
51+
}

0 commit comments

Comments
 (0)