《LeetCode力扣练习》代码随想录——双指针法(三数之和—Java)
刷题思路来源于 代码随想录
15. 三数之和
-
双指针
class Solution {public List<List<Integer>> threeSum(int[] nums) {List<List<Integer>> result=new ArrayList<>();if(nums.length==3&&nums[0]+nums[1]+nums[2]==0){result.add(Arrays.asList(nums[0],nums[1],nums[2]));return result;}Arrays.sort(nums);for(int i=0;i<nums.length;i++){if(nums[i]>0){break;}if(i>0&&nums[i]==nums[i-1]){continue;}int left=i+1;int right=nums.length-1;while(left<right){int temp=nums[i]+nums[left]+nums[right];if(temp>0){right--;}else if(temp<0){left++;}else{result.add(Arrays.asList(nums[i],nums[left],nums[right]));while(left<right&&nums[left]==nums[left+1]){left++;}left++;while(left<right&&nums[right-1]==nums[right]){right--;}right--;}}}return result;} }