python 18.4sum.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 18.4sum.py相关的知识,希望对你有一定的参考价值。

# Time: O(n^3)
# Space: O(1)
# 18. 4sum 
# Edge case 
'''
1. IO 
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]
]
'''

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums = sorted(nums)
        result = []
        for i in range(len(nums)-3):
            if i==0 or nums[i] != nums[i-1]:
                for j in range(i+1, len(nums)-2):
                    if j == i+1 or nums[j] != nums[j-1]:
                        left = j + 1
                        right = len(nums) - 1
                        sum = target - nums[i] - nums[j]
                        while left < right:
                            if nums[left] + nums[right] < sum:
                                left += 1
                            elif nums[left] + nums[right] > sum:
                                right -= 1
                            else:
                                result.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 result

以上是关于python 18.4sum.py的主要内容,如果未能解决你的问题,请参考以下文章

python 15. 3Sum.py

python 列出具有multi和sum.py的压缩

Ubuntu18.4—GDAL

Aspose.HTML for .NET 18.4改进了图像渲染

18.4Sum

18.4 Android 下原生Linux驱动测试