Last active
March 16, 2019 12:31
-
-
Save thieunguyencrystal/79822fd346952d8959e8001167c93e68 to your computer and use it in GitHub Desktop.
a+b+c+d=target
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public List<List<Integer>> fourSum(int[] num, int target) { | |
ArrayList <List<Integer>> resultList = new ArrayList<>(); | |
int length = num.length; | |
if (length < 4) | |
return resultList; | |
Arrays.sort(num); | |
for (int i = 0; i < length - 3; i++) { | |
if (i > 0 && num[i] == num[i - 1]) continue; | |
for (int j = i + 1; j < length - 2; j++) { | |
if (j > i + 1 && num[j] == num[j - 1]) continue; | |
int low = j + 1, high = length - 1; | |
while (low < high) { | |
int sum = num[i] + num[j] + num[low] + num[high]; | |
if (sum == target) { | |
List<Integer> result = Arrays.asList(num[i], num[j], num[low], num[high]); | |
resultList.add(result); | |
while (num[high] == num[high - 1] && low < high) | |
high = high - 1; | |
while (num[low] == num[low + 1] && low < high) | |
low = low + 1; | |
high = high - 1; | |
low = low + 1; | |
} else if (sum > target) | |
high = high - 1; | |
else | |
low = low + 1; | |
} | |
} | |
} | |
return resultList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment