diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index b94ebeef..dae8636b 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -311,7 +311,49 @@ var fourSum = function(nums, target) { }; ``` +TypeScript: + +```typescript +function fourSum(nums: number[], target: number): number[][] { + nums.sort((a, b) => a - b); + let first: number = 0, + second: number, + third: number, + fourth: number; + let length: number = nums.length; + let resArr: number[][] = []; + for (; first < length; first++) { + if (first > 0 && nums[first] === nums[first - 1]) { + continue; + } + for (second = first + 1; second < length; second++) { + if ((second - first) > 1 && nums[second] === nums[second - 1]) { + continue; + } + third = second + 1; + fourth = length - 1; + while (third < fourth) { + let total: number = nums[first] + nums[second] + nums[third] + nums[fourth]; + if (total === target) { + resArr.push([nums[first], nums[second], nums[third], nums[fourth]]); + third++; + fourth--; + while (nums[third] === nums[third - 1]) third++; + while (nums[fourth] === nums[fourth + 1]) fourth--; + } else if (total < target) { + third++; + } else { + fourth--; + } + } + } + } + return resArr; +}; +``` + PHP: + ```php class Solution { /**