forked from prakashshuklahub/Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15 3Sum
More file actions
56 lines (40 loc) · 1.39 KB
/
15 3Sum
File metadata and controls
56 lines (40 loc) · 1.39 KB
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
48
49
50
51
52
53
54
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.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
List<List<Integer>> res = new ArrayList();
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
for(int i=0;i<nums.length;i++){
if(i==0 || nums[i-1]!=nums[i]){
twoSumSorted(i+1,nums.length-1,nums,0-nums[i]);
}
}
return res;
}
void twoSumSorted(int i,int j,int[] nums,int target){
int a1 = nums[i-1];
while(i<j){ //search space
if(nums[i]+nums[j]>target){
j--;
}else if(nums[i]+nums[j]<target){
i++;
}else{
List<Integer> list = new ArrayList();
list.add(a1);list.add(nums[i]);list.add(nums[j]);
res.add(list);
//duplicate b
while(i<j && nums[i]==nums[i+1])i++;
//duplicate c
while(i<j && nums[j]==nums[j-1])j--;
i++;j--;
}
}
}