|
| 1 | +/** |
| 2 | + * 18. 4Sum |
| 3 | + * https://leetcode.com/problems/4sum/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an array nums of n integers, return an array of all the unique |
| 7 | + * quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: |
| 8 | + * - 0 <= a, b, c, d < n |
| 9 | + * - a, b, c, and d are distinct. |
| 10 | + * - nums[a] + nums[b] + nums[c] + nums[d] == target |
| 11 | + * |
| 12 | + * You may return the answer in any order. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[]} nums |
| 17 | + * @param {number} target |
| 18 | + * @return {number[][]} |
| 19 | + */ |
| 20 | +var fourSum = function(nums, target) { |
| 21 | + const result = []; |
| 22 | + |
| 23 | + nums.sort((a, b) => a - b); |
| 24 | + |
| 25 | + for (let i = 0; i < nums.length - 3; i++) { |
| 26 | + for (let j = i + 1; j < nums.length - 2; j++) { |
| 27 | + let high = nums.length - 1; |
| 28 | + let low = j + 1; |
| 29 | + |
| 30 | + while (low < high) { |
| 31 | + const sum = nums[i] + nums[j] + nums[low] + nums[high]; |
| 32 | + |
| 33 | + if (sum === target) { |
| 34 | + result.push([nums[i], nums[j], nums[low], nums[high]]); |
| 35 | + while (nums[low] === nums[low + 1]) { |
| 36 | + low++; |
| 37 | + } |
| 38 | + while (nums[high] === nums[high - 1]) { |
| 39 | + high--; |
| 40 | + } |
| 41 | + low++; |
| 42 | + high--; |
| 43 | + } else if (sum < target) { |
| 44 | + low++; |
| 45 | + } else { |
| 46 | + high--; |
| 47 | + } |
| 48 | + } |
| 49 | + while (nums[j] === nums[j + 1]) { |
| 50 | + j++; |
| 51 | + } |
| 52 | + } |
| 53 | + while (nums[i] === nums[i + 1]) { |
| 54 | + i++; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return result; |
| 59 | +}; |
0 commit comments