4Sum Leetcode Python

Given an array S of n integers, are there elements a, b, c, 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)

这题的解法和前面3sum的区别在于如果采用之前的解法,时间复杂度变为O(n^3) 因此我们考虑采用hash tale来用空间换时间。 基本做法是先把两两的和作为key存在hashtable,对应的 value是两两值的index.

然后再遍历时候用target -num[i]-num[j] 如果得到的差值还在hashtable里面就将其组合成所要的解。 时间复杂度为O(n^2) 空间复杂度为O (n^2)(这里我还在考虑因为是两两选出来,所以应该有C(n,2)个)

We can trade space with time in this problem. first iterate the num and use 2 sum as the key ,indexes as the value in hastable.

Then we start iterate again. take target -num[i]-num[j],if it is still in the hashtable, we take out the values and make the solution. The overall time and space complexity are both O(n^2)

code:

class Solution:
    # @return a list of lists of length 4, [[val1,val2,val3,val4]]
    def fourSum(self, num, target):
        solution=[]
        num.sort()
        dict={}
        if len(num)<4:
            return solution
        for i in range(len(num)):
            #if i>0 and num[i]==num[i+1]:
             #   continue
            for j in range(i+1,len(num)):
                val=num[i]+num[j]
                if val not in dict:
                    dict[val]=[[i,j]]
                else:
                    dict[val].append([i,j])
        for i in range(len(num)):
           # if i>0 and num[i]==num[i+1]:
            #    continue
            for j in range(i+1,len(num)-2):
                dif=target-num[i]-num[j]
                if dif in dict:
                    for k in dict[dif]:
                        if k[0]>j and [num[i],num[j],num[k[0]],num[k[1]]] not in solution:
                            solution.append([num[i],num[j],num[k[0]],num[k[1]]])
        return solution
        
时间: 2024-08-09 17:21:08

4Sum Leetcode Python的相关文章

[Leetcode]@python 62. Unique Paths

题目链接:https://leetcode.com/problems/unique-paths/ 题目大意:给定n.m,在mxn的矩阵中,从(0,0)走到(m-1,n-1)一共有多少种法(只能往下和往右走) 解题思路:从(0,0)到(m-1,n-1)一共要走m - 1次向下,n-1次向右.也就是在n + m - 2次中选出m-1次向下,也就是C(m + n - 2,m-1) class Solution(object): def uniquePaths(self, m, n): ""&

Pascal&#39;s triangle II Leetcode Python

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 这题和前面一题的区别在于不用返回所有解,只需要返回index对应行就行.做法和前面的一样定义一个currow 和prerow class Solu

[LeetCode][Python]18: 4Sum

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 18: 4Sumhttps://oj.leetcode.com/problems/4sum/ Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target?Find all unique quadruplets in the array

LeetCode Python 位操作 1

Python 位操作: 按位与 &, 按位或 | 体会不到 按位异或 ^ num ^ num = 0 左移 << num << 1 == num * 2**1 右移 >> num >> 2 == num / 2**2 取反 ~ ~num == -(num + 1) 1. Single Number Given an array of integers, every element appears twice except for one. Find

[Leetcode][Python]52: N-Queens II

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 52: N-Queens IIhttps://oj.leetcode.com/problems/n-queens-ii/ Follow up for N-Queens problem.Now, instead outputting board configurations, return the total number of distinct solutions. ===Comm

[Leetcode][Python]41: First Missing Positive

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 41: First Missing Positivehttps://oj.leetcode.com/problems/first-missing-positive/ Given an unsorted integer array, find the first missing positive integer.For example,Given [1,2,0] return 3,a

[LeetCode][Python]Intersection of Two Arrays II

Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as many times as it shows in both arrays

[Leetcode][Python]54: Spiral Matrix

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 54: Spiral Matrixhttps://leetcode.com/problems/spiral-matrix/ Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.For example,Given the foll

[Leetcode][Python]39: Combination Sum

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 39: Combination Sumhttps://oj.leetcode.com/problems/combination-sum/ Given a set of candidate numbers (C) and a target number (T),find all unique combinations in C where the candidate numbers