Skip to content

Commit

Permalink
solution(java): 18. 4Sum
Browse files Browse the repository at this point in the history
18. 4Sum
- Java
  • Loading branch information
godkingjay authored Oct 17, 2023
2 parents ec2cf5f + 4861119 commit 0723b6f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 32 deletions.
32 changes: 0 additions & 32 deletions Hard/10. Regular Expression Matching/soljava.java

This file was deleted.

50 changes: 50 additions & 0 deletions Medium/18. 4Sum/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);

for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}

for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}

int k = j + 1;
int l = nums.length - 1;

while (k < l) {
long sum = (long) nums[i] + nums[j] + nums[k] + nums[l];

if (sum == target) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
temp.add(nums[l]);
ans.add(temp);

k++;
l--;

while (k < l && nums[k] == nums[k - 1]) {
k++;
}

while (k < l && nums[l] == nums[l + 1]) {
l--;
}
} else if (sum < target) {
k++;
} else {
l--;
}
}
}
}
return ans;
}
}

0 comments on commit 0723b6f

Please sign in to comment.