3Sum and 4Sum @ Python Leetcode

1) 3Sum 

https://oj.leetcode.com/problems/3sum/

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)
class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):
        num.sort()
        ans = []
        target = 0
        for i in range(0, len(num)):
            if (i > 0 and num[i] == num[i-1]): continue  # only reserve first of all same values
            l, r = i + 1, len(num) - 1
            while l < r:
                sum = num[i] + num[l] + num[r]
                if sum == target:
                    ans.append([num[i], num[l], num[r]])
                    while l < r and num[l] == num[l + 1]: l = l + 1  # remove duplicate
                    while l < r and num[r] == num[r - 1]: r = r - 1  # remove duplicate
                    l, r = l + 1, r - 1
                elif sum < target:
                    l = l + 1
                else:
                    r = r - 1
        return ans

2) 4Sum

https://oj.leetcode.com/problems/4sum/

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)
class Solution:
    # @return a list of lists of length 4, [[val1,val2,val3,val4]]
    def fourSum(self, num, target):
        num.sort()
        ans = []
        for i in range(0, len(num)):
            if (i > 0 and num[i] == num[i-1]): continue  # only reserve first of all same values
            for j in range(i+1, len(num)):
                if (j > i + 1 and num[j] == num[j-1]): continue  # only reserve first of all same values
                l, r = j + 1, len(num) - 1
                while l < r:
                    sum = num[i] + num[j] + num[l] + num[r]
                    if sum == target:
                        ans.append([num[i], num[j], num[l], num[r]])
                        while l < r and num[l] == num[l + 1]: l = l + 1  # remove duplicate
                        while l < r and num[r] == num[r - 1]: r = r - 1  # remove duplicate
                        l, r = l + 1, r - 1
                    elif sum < target:
                        l = l + 1
                    else:
                        r = r - 1
        return ans
时间: 2024-07-29 17:28:48

3Sum and 4Sum @ Python Leetcode的相关文章

[leetcode]4Sum @ Python

原题地址:http://oj.leetcode.com/problems/4sum/ 题意:从数组中找到4个数,使它们的和为target.要求去重,可能有多组解,需要都找出来. 解题思路:一开始想要像3Sum那样去解题,时间复杂度为O(N^3),可无论怎么写都是Time Limited Exceeded.而同样的算法使用C++是可以通过的.说明Python的执行速度比C++慢很多.还说明了一点,大概出题人的意思不是要让我们去像3Sum那样去解题,否则这道题就出的没有意义了.这里参考了kitt的解

leetcode 3Sum 3Sum Closest 4Sum

这几个题很典型也是国外一些知名公司经常会问到的题 3Sum: 排序,避免重复,时间复杂度O(n^2) class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { int len=num.size(); sort(num.begin(),num.begin()+len); vector<vector<int> > ret; ret.clear(); i

[LeetCode] K sum(2Sum、3Sum、4Sum)

1 2Sum Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please not

leetcode: 2Sum/3Sum/3SumClosest/4Sum系列问题(转载)

转载:http://blog.csdn.net/li4951/article/details/8693212 leetcode上有好几道关于数组中几个数据和为target的题目.恰好正在看剑指offer中"和为s的两个数组这章",据此思想,leetcode上的三道题目都被我解决了.总结一下. 1.twoSum: 输入一个递增数组和一个数字s,在数组中查找两个数使得它们的和正好是s. 既然题目中已经提到了"递增数组",那么肯定不会暴力了.因此肯定有<O(n*n)

python leetcode 日记 --Contains Duplicate II --219

题目: Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and jis at most k. 给定一个整形数组和一个整数型数k,找出在这个数组中是否存在两个相同的数,并且这两个数的下标的距离小于k. "&q

1. Two Sum&amp;&amp;15. 3Sum&amp;&amp;18. 4Sum

题目: 1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Given nums = [2, 7, 1

Python LeetCode(七)

不会做 1. Search in Rotated Sorted Array 这道题的目的不在于解决它,而是如何更快的解决,这要求更低的时间复杂度,因此任何时间复杂度为n的方案应该都要被否决掉,只有n/2的解决方案才能被留下来. 这题不能简单的用二分查找的方式来做,因为它并不知道那个旋转的点在哪,因此并不知道应该向哪个方向移动,所以我们要确定target和mid是哪个方向的,像在二分查找中,如果 mid > target,则会将 right 移动到 mid 的位置,但其实不对,因为你并不知道此时m

2sum、3sum、4sum以及任意连续的数的和为sum、任意连续或者不连续的数的和为sum

2sum 如果数组是无序的,先排序(n*logn),然后用两个指针i,j,各自指向数组的首尾两端,令i=0,j=n-1,然后i++,j--,逐次判断a[i]+a[j]?=sum,如果某一刻a[i]+a[j]>sum,则要想办法让sum 的值减小,所以此刻i 不动,j--,如果某一刻a[i]+a[j]<sum,则要想办法让sum 的值增大,所以此刻i++,j 不动.所以,数组无序的时候,时间复杂度最终为O(n*logn+n)=O(n*logn),若原数组是有序的,则不需要事先的排序,直接O(n)

[python leetcode] Word Ladder II (very hard)[非常难,放弃]

Word Ladder II 描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: • Only one letter can be changed at a time • Each intermediate word must exist in the dictionary For examp