首页 > 其他 > 详细

leetcode 每日一题 18. 四数之和

时间:2020-04-30 12:49:51      阅读:70      评论:0      收藏:0      [点我收藏+]

技术分享图片

双指针法

思路:

参考三数之和,在外面多嵌套一层

代码:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        if len(nums) < 4:
            return []
        output = []
        nums.sort()
        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
                L = j+1
                R = len(nums)-1
                while L<R:
                    if nums[i]+nums[j]+nums[L]+nums[R] == target:
                        output.append([nums[i],nums[j],nums[L],nums[R]])
                        while L<R and nums[L+1] == nums[L]:
                            L += 1
                        while L<R and nums[R-1] == nums[R]:
                            R -= 1
                        L +=1
                        R -=1
                    elif nums[i]+nums[j]+nums[L]+nums[R] < target:
                        L +=1
                    else:
                        R -=1
        return output

 

leetcode 每日一题 18. 四数之和

原文:https://www.cnblogs.com/nilhxzcode/p/12808053.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!