Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Use two for loops for 2 elements and then iterate the rest of the array using two pointer, and once the target matches,push it into the ans.second loop should start after the first one ends.
- Trick:
- Skip the continous duplicates on all the 4 pointers, i,j,l,r
- '''
- class Solution:
- def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
- # ans=set()
- nums.sort()
- ans=[]
- for i in range(len(nums)):
- if i>0 and nums[i]==nums[i-1]: #skip the continous duplicates as one appearance for each number
- continue
- for j in range(i+1,len(nums)):
- if j>i+1 and nums[j]==nums[j-1]: #skip the continous duplicates as one appearance for each number but it has to skip the previous jth element, not the previous ith element(2,2,2,2) os j>i+1
- continue
- l=j+1
- r=len(nums)-1
- while l<r:
- if nums[l]+nums[r]+nums[i]+nums[j]==target:
- ans.append((nums[i],nums[j],nums[l],nums[r]))
- l+=1
- r-=1
- while l<r and nums[l]==nums[l-1]: #skip the continous duplicates as one appearance for each number
- l+=1
- while r>l and nums[r]==nums[r+1]: #skip the continous duplicates as one appearance for each number
- r-=1
- elif nums[l]+nums[r]+nums[i]+nums[j]>target:
- r-=1
- else:
- l+=1
- return ans
Advertisement
Add Comment
Please, Sign In to add comment