🚩传送门:牛客题目

题目

给出一个有 [NC]54. 数组中相加和为 0 的三元组 - 图1 个元素的数组[NC]54. 数组中相加和为 0 的三元组 - 图2[NC]54. 数组中相加和为 0 的三元组 - 图3中是否有元素[NC]54. 数组中相加和为 0 的三元组 - 图4 满足 [NC]54. 数组中相加和为 0 的三元组 - 图5找出数组[NC]54. 数组中相加和为 0 的三元组 - 图6中所有满足条件的三元组。

注意:

  1. 三元组[NC]54. 数组中相加和为 0 的三元组 - 图7中的元素必须按非降序排列。(即[NC]54. 数组中相加和为 0 的三元组 - 图8
  2. 解集中不能包含重复的三元组。

示例 1:

输入:[-10,0,10,20,-10,-40] 输出:[[-10,-10,20],[-10,0,10]]

解题思路:双指针

  1. 首先对数组进行排序(从小到大)
  2. 依次取出数组中的每个数作为 [NC]54. 数组中相加和为 0 的三元组 - 图9 ,并且不重复的选取(跳过重复的数)
  3. 这样问题就转换为 _2_ 个数求和的问题(可以用双指针解决方法)
    • [NC]54. 数组中相加和为 0 的三元组 - 图10**_right-- _**
    • [NC]54. 数组中相加和为 0 的三元组 - 图11**_left++_**
    • [NC]54. 数组中相加和为 0 的三元组 - 图12**_right--,left++_**(跳过重复的数)


官方代码

  1. class Solution {
  2. public static List<List<Integer>> threeSum(int[] nums) {
  3. Arrays.sort(nums);
  4. List<List<Integer>> res = new ArrayList<>();
  5. for (int i = 0; i < nums.length - 2; i++) {
  6. if (nums[i] > 0) break; // 因为排序后 nums[j] >= nums[i] >= nums[i] > 0
  7. if (i > 0 && nums[i] == nums[i - 1]) continue; // target去重
  8. int left = i + 1, right = nums.length - 1;
  9. while (left < right) {
  10. int sum = nums[i] + nums[left] + nums[right];
  11. if (sum < 0) {
  12. left++;
  13. } else if (sum > 0) {
  14. right--;
  15. } else {
  16. res.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[left], nums[right])));
  17. while (left < right && nums[left] == nums[++left]) ;
  18. while (left < right && nums[right] == nums[--right]) ;
  19. }
  20. }
  21. }
  22. return res;
  23. }
  24. }