2022-4-29 双指针
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
1 class Solution { 2 public List<List<Integer>> threeSum(int[] nums) { 3 List<List<Integer>> list=new ArrayList<>(); 4 Arrays.sort(nums); 5 int index=0,n=nums.length; 6 while (index<n){ 7 int target=-nums[index]; 8 int l=index+1,r=n-1; 9 while (l<r){ 10 int sum=nums[l]+nums[r]; 11 int left=nums[l],right=nums[r]; 12 if (sum<target){ 13 while (l<r&&nums[l]==left) l++; 14 }else if (sum>target){ 15 while (l<r&&nums[r]==right) r--; 16 }else{ 17 list.add(List.of(-target,left,right)); 18 while (l<r&&nums[l]==left) l++; 19 while (l<r&&nums[r]==right) r--; 20 } 21 } 22 while (index<n&&nums[index]==-target) index++; 23 } 24 return list; 25 } 26 }
思路:2sum的基础上,穷举第一个数字。
浙公网安备 33010602011771号