Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/leslie-23/leetcode-4sum
FourSum problem in leetcode
https://github.com/leslie-23/leetcode-4sum
Last synced: 23 days ago
JSON representation
FourSum problem in leetcode
- Host: GitHub
- URL: https://github.com/leslie-23/leetcode-4sum
- Owner: Leslie-23
- Created: 2024-07-30T14:06:46.000Z (6 months ago)
- Default Branch: main
- Last Pushed: 2024-07-30T14:13:03.000Z (6 months ago)
- Last Synced: 2024-11-06T17:33:14.718Z (2 months ago)
- Language: JavaScript
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
```
/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
const result = [];if (nums == null || nums.length < 4) {
return result;
}nums.sort((a, b) => a - b);
const len = nums.length;
for (let i = 0; i < len - 3; i++) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
for (let j = i+1; j < len - 2; j++) {
if (j > i+1 && nums[j] == nums[j-1]) {
continue;
}
let left = j + 1;
let right = len - 1;
while (left < right) {
const sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.push([nums[i], nums[j], nums[left], nums[right]]);while (left < right && nums[left] == nums[left+1]) {
left++;
}while (left < right && nums[right] == nums[right-1]) {
right--;
}left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}return result
};
```