zoukankan      html  css  js  c++  java
  • 18. 4Sum

    给定一个包含 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

    3sum多层for

    class Solution:
        def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
            if len(nums)<4:return []
            res=[]
            nums.sort()
            n=len(nums)
            for i in range(n-3):
                if i!=0 and nums[i]==nums[i-1]:
                    continue
                for j in range(i+1,n-2):
                    if j!=i+1 and nums[j]==nums[j-1]:
                        continue
                    l=j+1
                    r=n-1
                    while l<r:
                        sum=nums[i]+nums[j]+nums[l]+nums[r]
                        if sum<target:
                            l+=1
                        elif sum>target:
                            r-=1
                        else:
                            res.append([nums[i],nums[j],nums[l],nums[r]])
                            l+=1
                            r-=1
                            while l<r and nums[l]==nums[l-1]:l+=1
                            while l<r and nums[r]==nums[r+1]:r-=1
            return res
  • 相关阅读:
    hive基本操作与应用
    理解MapReduce计算构架
    熟悉HBase基本操作
    熟悉常用的HDFS操作
    爬虫大作业
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    Hadoop综合大作业
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13769838.html
Copyright © 2011-2022 走看看