Skip to content

Commit 12a9561

Browse files
Accepted
1 parent 62f4059 commit 12a9561

File tree

2 files changed

+117
-0
lines changed

2 files changed

+117
-0
lines changed

problems/src/FourSum.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
/**
6+
* Created by gouthamvidyapradhan on 29/03/2017.
7+
* Accepted
8+
*/
9+
public class FourSum
10+
{
11+
12+
/**
13+
* Main method
14+
* @param args
15+
* @throws Exception
16+
*/
17+
public static void main(String[] args) throws Exception
18+
{
19+
int[] nums = {1, 0, -1, 0, -2, 2};
20+
System.out.println(new FourSum().fourSum(nums, 0));
21+
}
22+
23+
public List<List<Integer>> fourSum(int[] nums, int target)
24+
{
25+
List<List<Integer>> result = new ArrayList<>();
26+
if(nums.length < 4) return result;
27+
Arrays.sort(nums);
28+
for(int i = 0; i < nums.length - 3; i++)
29+
{
30+
if(i == 0 || nums[i] != nums[i - 1])
31+
{
32+
for(int j = i + 1; j < nums.length - 2; j ++)
33+
{
34+
if(j == i + 1 || nums[j] != nums[j - 1])
35+
{
36+
int k = j + 1, l = nums.length - 1;
37+
while(k < l)
38+
{
39+
if(k != j + 1 && nums[k] == nums[k + 1])
40+
{
41+
k++; continue;
42+
}
43+
int sum = nums[i] + nums[j] + nums[k] + nums[l];
44+
if(sum == target)
45+
{
46+
result.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
47+
k++; l --;
48+
}
49+
else if(sum < target)
50+
{
51+
k ++;
52+
}
53+
else
54+
{
55+
l --;
56+
}
57+
}
58+
}
59+
}
60+
}
61+
}
62+
return result;
63+
}
64+
65+
}

problems/src/ThreeSum.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
/**
6+
* Created by gouthamvidyapradhan on 29/03/2017.
7+
* Accepted
8+
*/
9+
public class ThreeSum
10+
{
11+
/**
12+
* Main method
13+
* @param args
14+
* @throws Exception
15+
*/
16+
public static void main(String[] args) throws Exception
17+
{
18+
int[] nums = {-1,0,1,2,-1,-4,-1,0,1,2,-1,-4,-1,0,1,2,-1,-4,-1,0,1,2,-1,-4,-1,0,1,2,-1,-4,-1,0,1,2,-1,-4,-1,0,1,2,-1,-4,-1,0,1,2,-1,-4};
19+
System.out.println(new ThreeSum().threeSum(nums));
20+
}
21+
22+
public List<List<Integer>> threeSum(int[] nums)
23+
{
24+
List<List<Integer>> result = new ArrayList<>();
25+
if(nums.length < 3) return result;
26+
Arrays.sort(nums);
27+
for(int i = 0, l = nums.length; i < l - 2; i ++)
28+
{
29+
if(i == 0 || nums[i] != nums[i - 1])
30+
{
31+
int j = i + 1, k = l - 1;
32+
while(k > j)
33+
{
34+
if(j != i + 1 && nums[j] == nums[j - 1])
35+
{
36+
j ++;
37+
continue;
38+
}
39+
int sum = nums[i] + nums[j] + nums[k];
40+
if(sum == 0)
41+
{
42+
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
43+
k--; j++;
44+
}
45+
else if(sum > 0) k--;
46+
else j++;
47+
}
48+
}
49+
}
50+
return result;
51+
}
52+
}

0 commit comments

Comments
 (0)