Leetcode-the sum of four problems

topic:

Given an array nums containing n integers and a target value target, judge whether there are four elements a, b, c, and d in nums so that the value of a + b + c + d is equal to target? Find all four-tuples that meet the conditions and do not repeat.

Note: The
answer cannot contain repeated quadruples.

Example:

Given the array nums = [1, 0, -1, 0, -2, 2], and target = 0.

The set of quadruples that meet the requirements are: [[-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2]]

Ideas:

  1. The overall idea is not much different from the previous blog "Sum of Three Numbers", it is still a sort + double pointer issue. After sorting the nums array, you may wish to set the left node a, set the initial value of the left pointer b=a+1, the right node d, and the initial value of the right pointer c=d-1.
  2. When the length of the nums array is less than 4, an empty list is returned directly.
  3. A double nested loop is performed on the left node a and the right node d, the purpose is to maintain the relative invariance of the left and right nodes when the left and right pointers move .
  4. When a+b+c+d-target=0, add it to the list; when a+b+c+d-target<0, b++; when a+b+c+d-target>0, c- -.
  5. At the same time, the problem of repeated values ​​should be considered. For the left node a and the right node d, a judgment is made at the beginning of the loop. When the left and right nodes move and are the same as the previous node, keep moving: a++, d- -.
  6. For the left and right pointers c, d, after each movement operation, it is judged again whether it is the same as the previous value, and if yes, the movement is continued.

code show as below:
Insert picture description here

Test Results:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41570890/article/details/109258951