标签:get span sel pre etc targe app sort nbsp
和三数之和思路一样,先排序,再双指针。
class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> res = new ArrayList<>(); if(nums.length==0){return res;} for(int i1=0;i1<nums.length-3;i1++){ if(i1>0&&nums[i1-1]==nums[i1]){continue;} for(int i2=i1+1;i2<nums.length-2;i2++){ if( i2>i1+1&&nums[i2-1]==nums[i2]){continue;} int i3=i2+1; int i4=nums.length-1; while(i3<i4){ if(nums[i1]+nums[i2]+nums[i3]+nums[i4]==target){ res.add(Arrays.asList(nums[i1],nums[i2],nums[i3],nums[i4])); while(i3<i4&&nums[i3+1]==nums[i3]){i3++;} while(i3<i4&&nums[i4-1]==nums[i4]){i4--;} i3++; i4--; }else if(nums[i1]+nums[i2]+nums[i3]+nums[i4]<target){ i3++; }else{ i4--; } } } } return res; } }
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: if not nums:return [] nums.sort() res = [] for i1 in range(len(nums)-3): if i1>0 and nums[i1]==nums[i1-1]: continue for i2 in range(i1+1, len(nums)-2): if i2>i1+1 and nums[i2]==nums[i2-1]: continue i3 = i2+1 i4 = len(nums)-1 while i3<i4: if nums[i1]+nums[i2]+nums[i3]+nums[i4]==target: res.append([nums[i1],nums[i2],nums[i3],nums[i4]]) while i3<i4 and nums[i3+1]==nums[i3]: i3+=1 while i3<i4 and nums[i4-1]==nums[i4]: i4-=1 i3+=1 i4-=1 elif nums[i1]+nums[i2]+nums[i3]+nums[i4]<target: i3+=1 else: i4-=1 return res
标签:get span sel pre etc targe app sort nbsp
原文地址:https://www.cnblogs.com/huangzengrui/p/12452577.html