Created
November 1, 2021 22:26
-
-
Save AndreVallestero/af5047fbd69c34d1c7db875edc5acf04 to your computer and use it in GitHub Desktop.
Solution for 4 sum problem, has duoTarget optimization for 33% speedup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def fourSum(self, nums: List[int], target: int) -> List[List[int]]: | |
lenNums = len(nums) | |
nums.sort() | |
quads = [] | |
for i in range(lenNums - 3): | |
if nums[i] == nums[i-1] and i > 0: continue | |
for j in range(i + 1, lenNums - 2): | |
if nums[j] == nums[j-1] and j > i + 1: continue | |
k = j + 1 | |
l = lenNums - 1 | |
duoTarget = target - nums[i] - nums[j] | |
while k < l : | |
duoSum = nums[k] + nums[l] | |
if duoSum < duoTarget: | |
k += 1 | |
elif duoSum > duoTarget: | |
l -= 1 | |
else: | |
quads.append([nums[i], nums[j], nums[k], nums[l]]) | |
k += 1 | |
while nums[k] == nums[k-1] and k < l: k += 1 | |
return quads |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment