挑战算法题:四数之和

x33g5p2x  于9个月前 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(618)

昨天解决了三数之和,感兴趣或者不知道怎么解的同学可以先看双指针妙解三数之和,今天继续试试解开:四数之和。
变量变多了一个,但是难度还是medium,因为思路是类似的。
具体题目如下所示:

  1. Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
  2. 0 <= a, b, c, d < n
  3. a, b, c, and d are distinct.
  4. nums[a] + nums[b] + nums[c] + nums[d] == target
  5. You may return the answer in any order.
  6. Example 1:
  7. Input: nums = [1,0,-1,0,-2,2], target = 0
  8. Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
  9. Example 2:
  10. Input: nums = [2,2,2,2,2], target = 8
  11. Output: [[2,2,2,2]]
  12. Constraints:
  13. 1 <= nums.length <= 200
  14. -109 <= nums[i] <= 109
  15. -109 <= target <= 109

学习的过程就是搭积木的过程,解决问题的过程也是一样的,先想想可不可以把四数之和转化为三数问题。三数问题我们是把其中一个数字作为固定元素,通过循环去主义匹配剩下2个数字。而剩下两个数字就可以用两个指针不断移动,确定解法。同样的,四数问题,可以转换成2个循环去确定2个固定元素,剩下2个元素依然用双指针去移动确立。

代码实现如下所示:

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} target
  4. * @return {number[][]}
  5. */
  6. var fourSum = function(nums, target) {
  7. // Sort the array
  8. nums.sort((a, b) => a - b);
  9. const result = [];
  10. for (let i = 0; i < nums.length - 3; i++) {
  11. // Skip the duplicated items
  12. if (i > 0 && nums[i] === nums[i - 1]) continue;
  13. for (let j = i + 1; j < nums.length - 2; j++) {
  14. // Skip the duplicated items
  15. if (j > i + 1 && nums[j] === nums[j - 1]) continue;
  16. let left = j + 1;
  17. let right = nums.length - 1;
  18. while(left < right) {
  19. const sum = nums[i] + nums[j] + nums[left] + nums[right];
  20. if (sum === target) {
  21. result.push([nums[i], nums[j], nums[left], nums[right]]);
  22. while(left < right && nums[left] === nums[left+1]) {
  23. left += 1;
  24. }
  25. while(left < right && nums[right] === nums[right-1]) {
  26. right -= 1;
  27. }
  28. left += 1;
  29. right -= 1;
  30. } else if (sum > target) {
  31. right -= 1;
  32. } else {
  33. left += 1;
  34. }
  35. }
  36. }
  37. }
  38. return result;
  39. }

执行之后的效率中规中矩,如图所示:

到这里本该结束了,但是这个算法其实还有提升空间。在left和right指针跳过重复的值的过程,我们可以提前退出循环,如下所示:

  1. while(left < right) {
  2. const sum = nums[i] + nums[j] + nums[left] + nums[right];
  3. const remaining = target - sum;
  4. if (remaining > nums[right] - nums[left]) break; // Jump out the loop, because there is no item can match it
  5. }

重新提交之后,执行时间减少明显,内存使用保持不变:

总结

这一类求多个元素之和等于给定值的算法题,都可以用双指针去解决,注意感受指针移动的过程以及培养转化已知问题的能力。

相关文章