1) 3Sum
https://oj.leetcode.com/problems/3sum/
Given an array S of n integers, is there elements a, b, c in S such That a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,C) must is in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2-1-4}, A solution set is: ( -1, 0, 1) (-1,-1, 2)
classSolution:#@return A list of lists of length 3, [[Val1,val2,val3]] defthreesum (self, num): Num.sort () ans=[] Target=0 forIinchRange (0, Len (num)):if(I > 0 andNum[i] = = Num[i-1]):Continue #Reserve first of all same valuesL, R = i + 1, len (num)-1 whileL <R:sum= Num[i] + num[l] +Num[r]ifsum = =target:ans.append ([Num[i], num[l], num[r]) whileL < R andNum[l] = = num[l + 1]: L = l + 1#Remove Duplicate whileL < R andNum[r] = = Num[r-1]: R = r-1#Remove DuplicateL, R = L + 1, r-1elifSum <target:l= L + 1Else: R= R-1returnAns
2) 4Sum
https://oj.leetcode.com/problems/4sum/
Given an array
S of
Nintegers, is there elements
a,
b,
C, and
Dinch
Ssuch that
a +
b +
C +
D= target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,D) must is in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0-1 0-2 2}, and target = 0. A solution set is: ( -1, 0, 0, 1) ( -2,-1, 1, 2) ( -2, 0, 0, 2)
classSolution:#@return A list of lists of length 4, [[Val1,val2,val3,val4]] deffoursum (self, num, target): Num.sort () ans= [] forIinchRange (0, Len (num)):if(I > 0 andNum[i] = = Num[i-1]):Continue #Reserve first of all same values forJinchRange (i+1, Len (num)):if(J > i + 1 andNUM[J] = = Num[j-1]):Continue #Reserve first of all same valuesL, R = j + 1, len (num)-1 whileL <R:sum= Num[i] + num[j] + num[l] +Num[r]ifsum = =target:ans.append ([Num[i], num[j], num[l], Num[r]]) whileL < R andNum[l] = = num[l + 1]: L = l + 1#Remove Duplicate whileL < R andNum[r] = = Num[r-1]: R = r-1#Remove DuplicateL, R = L + 1, r-1elifSum <target:l= L + 1Else: R= R-1returnAns
3Sum and 4Sum @ Python Leetcode