标签:public continue 情况 需要 跳过 双指针 leetcode twosum app
先排序,再用双指针,注意的是解中是没有重复的情况的,所以需要跳过。
class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); for(int i=0;i<nums.length;i++){ if(i>0&&nums[i]==nums[i-1]) continue; int l =i+1; int r= nums.length-1; int twoSum = 0-nums[i]; while(l<r){ if(nums[l]+nums[r]==twoSum){ res.add(Arrays.asList(nums[i], nums[l], nums[r])); while(l<r&&nums[l+1]==nums[l]) l++; while(l<r&&nums[r-1]==nums[r]) r--; l++; r--; }else if(nums[l]+nums[r]<twoSum) l++; else if(nums[l]+nums[r]>twoSum) r--; } } return res; } }
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] for i in range(len(nums)): if i>0 and nums[i]==nums[i-1]: continue; two_sum = - nums[i] l = i+1 r = len(nums)-1 while(l<r): if nums[l]+nums[r]==two_sum: res.append([nums[i], nums[l], nums[r]]) while(l<r and nums[l]==nums[l+1]):l+=1 while(l<r and nums[r]==nums[r-1]):r-=1 l+=1 r-=1 elif nums[l]+nums[r]<two_sum:l+=1 else:r-=1 return res
标签:public continue 情况 需要 跳过 双指针 leetcode twosum app
原文地址:https://www.cnblogs.com/huangzengrui/p/12424122.html