Python 刷题日记:LeetCode: 1&15&16-Two Sum and 3Sum

来源:互联网 发布:云计算控制节点 编辑:程序博客网 时间:2024/06/05 06:08

这篇博文整理了关于做2Sum和3Sum的做题心得,这类题目都是给定一个整数数组和一个目标值,然后从数组中找出加和等于目标值的下标或值。

LeetCode 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.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

解题思路

1、最简单的思路就是两次遍历数组寻找与target相等的值,这样的做法时间复杂度为O(n^2),如果是三个数相加复杂度就变成了O(n^3),这样显然无法通过LeetCode的时间复杂度限制。
2、利用python中字典的特点,把每次遍历的值都存在字典中,下次要用的时候直接调用。这样的做法可以将复杂度降为O(n)。

def twoSum(nums,target):    dic={}   ##key存储nums里的数  value 存储下标    len_nums=len(nums)    for i in range(len_nums):        if target-nums[i] in dic:            return [dic[target-nums[i]],i]        else:            dic[nums[i]]=i

LeetCode 15:

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

Note: 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]]

解题思路

1、最简单的就是遍历,时间复杂度为O(n^3)。
2、设置两个j、k指针,负责前后移动。其实就是对每一个i,都寻找一遍使的nums[i]+nums[j]+nums[k]=0的值,这样的复杂度为O(n^2)。

def threeSum2(nums):    res = []    nums.sort()    for i in xrange(len(nums)-2):        if i > 0 and nums[i] == nums[i-1]:  #为了避免重复            continue        l, r = i+1, len(nums)-1    #设置两个指针,负责前后移动        while l < r:            s = nums[i] + nums[l] + nums[r]            if s < 0:                l +=1             elif s > 0:                r -= 1            else:                res.append((nums[i], nums[l], nums[r]))                while l < r and nums[l] == nums[l+1]:                    l += 1                while l < r and nums[r] == nums[r-1]:                    r -= 1                l += 1; r -= 1    return res

LeetCode 16:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

解题思路:

思路其实和上面一题一样,只是上面一题的基础上去除了“去重的部分”因为该题只需返回sum值。同时,设置了一个判断条件使得最接近target的值输出。

def threeSumClosest(num, target):    num.sort()    res = num[0] + num[1] + num[2]    for i in xrange(len(num) - 2):        j, k = i+1, len(num) - 1        while j < k:            s = num[i] + num[j] + num[k]            if s == target:                return sum            if abs(s - target) < abs(res - target):                res = s            if s < target:                j += 1            elif s > target:                k -= 1    return res