zoukankan      html  css  js  c++  java
  • leetcode------4Sum

    标题: 4Sum
    通过率: 21.4%
    难度: 中等

    Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

    Note:

    • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
    • The solution set must not contain duplicate quadruplets.
        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)

    4sum相当于在3sum外加一层循环:直接看代码:

     1 class Solution:
     2     # @return a list of lists of length 4, [[val1,val2,val3,val4]]
     3     def fourSum(self, num, target):
     4         num.sort()
     5         ans = []
     6         for j in range(len(num)):
     7             for i in range(j+1, len(num)):
     8                 l, r = i + 1, len(num) - 1
     9                 while l < r:
    10                     sum = num[j] + num[i] + num[l] + num[r] 
    11                     if sum == target:
    12                         tmp=[num[j],num[i], num[l], num[r]]
    13                         if tmp not in ans:
    14                             ans.append(tmp)
    15                         l, r = l + 1, r - 1
    16                     elif sum < target:
    17                         l = l + 1
    18                     else:
    19                         r = r - 1   
    20         return ans
  • 相关阅读:
    DOM_节点操作创建表格
    表单提交
    HTML常用标签
    网络通讯详解
    java===TCP(多线程多客户端同时上传字节数据:图片为例)
    java===TCP(文件上传功能)
    java===UDP
    java==IO=随机读写文件
    git中的基本命令
    ansible中roles的简单使用
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4403421.html
Copyright © 2011-2022 走看看