当前位置:   article > 正文

C++ | Leetcode C++题解之第18题四数之和

C++ | Leetcode C++题解之第18题四数之和

题目:

题解:

  1. class Solution {
  2. public:
  3. vector<vector<int>> fourSum(vector<int>& nums, int target) {
  4. vector<vector<int>> quadruplets;
  5. if (nums.size() < 4) {
  6. return quadruplets;
  7. }
  8. sort(nums.begin(), nums.end());
  9. int length = nums.size();
  10. for (int i = 0; i < length - 3; i++) {
  11. if (i > 0 && nums[i] == nums[i - 1]) {
  12. continue;
  13. }
  14. if ((long) nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
  15. break;
  16. }
  17. if ((long) nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
  18. continue;
  19. }
  20. for (int j = i + 1; j < length - 2; j++) {
  21. if (j > i + 1 && nums[j] == nums[j - 1]) {
  22. continue;
  23. }
  24. if ((long) nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
  25. break;
  26. }
  27. if ((long) nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) {
  28. continue;
  29. }
  30. int left = j + 1, right = length - 1;
  31. while (left < right) {
  32. long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
  33. if (sum == target) {
  34. quadruplets.push_back({nums[i], nums[j], nums[left], nums[right]});
  35. while (left < right && nums[left] == nums[left + 1]) {
  36. left++;
  37. }
  38. left++;
  39. while (left < right && nums[right] == nums[right - 1]) {
  40. right--;
  41. }
  42. right--;
  43. } else if (sum < target) {
  44. left++;
  45. } else {
  46. right--;
  47. }
  48. }
  49. }
  50. }
  51. return quadruplets;
  52. }
  53. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/427536
推荐阅读
相关标签
  

闽ICP备14008679号