Leetcode第十八题:四数之和

题目:

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

个人思路:

三指针法再加一层遍历?毫无思路。加一个毫字可以充分体现我的悲痛与无奈。

官方答案推荐:

还真就固定两点内部再用一个双指针法。。。O(n^3)。。。跟三指针那个基本没区别。

python代码:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        result = []
        if(len(nums) < 4):
            return result
        nums.sort()
        for start in range(len(nums) - 3):
            if start>0 and nums[start] == nums[start-1]:
                continue
            
            for end in range(len(nums)-1,start+2,-1):
                if end< len(nums)-1 and nums[end] == nums[end +1]:
                    continue
                left,right = start+1,end-1
                while left < right:
                    curResult = nums[start] + nums[end] + nums[left] + nums[right]
                    if(curResult > target):
                        right -=1
                    elif curResult < target: 
                        left +=1
                    else:
                        result.append([nums[start],nums[end],nums[left],nums[right]])
                        while left<right and nums[left] == nums[left+1]:
                            left +=1
                        while left<right and nums[right] == nums[right-1]:
                            right -=1
                        left +=1
                        right -=1
        return result



反思:

想多了。。。还有写代码的时候没有考虑到target<0的情况。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章