4 sum

题目描述

4 elements sum to target

解题方法

两个for loop,里面2 sum的two pointer方法

将two pointer写在for-loop里,可以减少function call导致的时间

Solution

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        length = len(nums)
        results = []

        for i in range(len(nums)-3):
            if i != 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1, len(nums)-2):
                if j!= i+1 and nums[j] == nums[j-1]:
                    continue

                left = j + 1
                right = length - 1
                while left < right:
                    curSum = nums[i] + nums[j] + nums[left] + nums[right]
                    if curSum > target:
                        right -= 1
                    elif curSum < target:
                        left += 1
                    else:
                        results.append([nums[i], nums[j], nums[left], nums[right]])
                        left += 1
                        right -= 1
                        while(left < right and nums[left] == nums[left-1]):
                            left += 1
                        while(left < right and nums[right] == nums[right+1]):
                            right -= 1

        return results