LeetCode[Array]----3Sum
3Sum
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:
- 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)
分析:
该题是LeetCode-Two Sum一题的升级版。
题目的要求是,给定一个数组,要求找到一组不重合的解(a,b,c),使得a + b + c等于0.
借鉴Two Sum题的(编程之美上的)思路,我们能够将当中的一个数a作为target,然后问题就转化为了求b + c等于-a的Two Sum问题。
详细解说一下:我们首先还是对数组nums进行排序。这样后面查找时就行使用双指针分别从前和从后向中间開始遍历了。
在排序后nums中依次从左边開始选择一个元素乘以-1作为target,然后使用左右两个指针分别从前和往后開始遍历,假设两指针的相应的元素和等于target。则将这三个元素存储作为一个解,然后左右指针分别向中间移动;假设两指针的相应元素和大于target,那么右指针向左移动。假设两指针的相应元素和小于target,那么左指针向右移动。
代码:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums) < 3:
return []
# 对数组进行排序。方便后面的查找
nums.sort()
for i in range(len(nums) - 2):
# 把a作为target
target = nums[i] * -1
# 问题转化为b+c == -a的情况了
a = i + 1
b = len(nums) - 1
while a < b:
if nums[a] + nums[b] == target:
res.append([nums[i], nums[a], nums[b]])
a += 1
b -= 1
elif nums[a] + nums[b] > target:
b -= 1
else:
a += 1
dummyres = []
# 因为上面的方法产生的解有反复,须要去重
for i in range(len(res)):
if res[i] in dummyres:
pass
else:
dummyres.append(res[i])
return dummyres
改进一下:
上面的代码产生的解中有反复,假设我们可以在求解的过程中过滤掉左/右指针移动后的元素值不发生变化这两种情况。就可以避免在求解过程中产生反复解。
改进的代码:
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums) < 3:
return []
nums.sort()
for i in range(len(nums) - 2):
# 当nums[i]大于0时。后面的元素和一定大于0,不须要再进行推断了
# 当nums[i]与前一个元素值同样时,解是同样的
if nums[i] > 0 or i and nums[i] == nums[i-1]:
continue
target = -nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
# 当nums[right]小于0时。a,b,c三个元素值都小于0。也不须要进行-a == b+c的推断了
if nums[right] < 0:
break
if nums[left] + nums[right] == target:
res.append([nums[i], nums[left], nums[right]])
while left < right and nums[left+1] == nums[left]: # 当nums[left]值与下一个元素值同样时,解同样
left += 1
while left < right and nums[right-1] == nums[right]:
right -= 1
left += 1
right -= 1
elif nums[left] + nums[right] > target:
right -= 1
else:
left += 1
return res
LeetCode[Array]----3Sum的更多相关文章
- [Leetcode][016] 3Sum Closest (Java)
题目: https://leetcode.com/problems/3sum-closest/ [标签]Array; Two Pointers [个人分析] 这道题和它的姊妹题 3Sum 非常类似, ...
- [LeetCode] 259. 3Sum Smaller 三数之和较小值
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- LeetCode 15 3Sum [sort] <c++>
LeetCode 15 3Sum [sort] <c++> 给出一个一维数组,找出其中所有和为零的三元组(元素集相同的视作同一个三元组)的集合. C++ 先自己写了一发,虽然过了,但跑了3 ...
- LeetCode 16. 3Sum Closest(最接近的三数之和)
LeetCode 16. 3Sum Closest(最接近的三数之和)
- Leetcode Array 16 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
- Array + two points leetcode.16 - 3Sum Closest
题面 Given an array nums of n integers and an integer target, find three integers in nums such that th ...
- Leetcode Array 15 3sum
思考的方向不对,即使用了多于别人几倍的时间,也不一定能够达到终点. 我的错误的想法(可以跳过):在leetcode上面做的第四道题,走路一个很大的弯路,收到之前做过的 Container With ...
- LeetCode (13): 3Sum Closest
https://leetcode.com/problems/3sum-closest/ [描述] Given an array S of n integers, find three integers ...
随机推荐
- SQLServer当数据导入平面文件
SQLServer当数据导入无发正常工作时候,可以尝试BULK命令操作 BULK INSERT [dbo].[test] FROM 'H:\testdb.csv' WITH( FIELDTERMINA ...
- jquery 异步处理
<!DOCTYPE html> <head> <script type="text/javascript" src="jquery-1.12 ...
- Navi.Soft31.开发工具(含下载地址)
1系统简介 1.1功能简述 在软件开发过程中,我们需要经常对字符串.文件.数据库操作.有时需要浏览Json格式串,有时需要浏览Xml格式串,有时需要读取txt或excel文件,有时需要对数据库访问.本 ...
- spring mvc中关于url中传递中文乱码的解决方法
在传值过程中,也是乱码出现的频繁地.先不说到底是什么场景了,通常常用的方案有如下几个 配置指定的filter <!-- 配置请求过滤器,编码格式设为UTF-8,避免中文乱码--> < ...
- 扫描二维码或其他操作情况下返回界面,onActivityResult()不执行的问题
在使用第三方zxing扫描时,部分手机(好像都是4.4及以下版本的手机)扫描后不调用onActivityResult()返回结果. 调试发现zxing的扫描界面CaptureActivity 在注册时 ...
- ubuntu eclipse&JDK
1. 下载jre,eclipse,cdt 其中jre是java运行环境,eclipse需要先装jre,才可能运行,cdt是在eclipse中运行c\c++程序的插件. 1.1 下载jre 网址是:ja ...
- 【转】【MySQL】Mysql模糊查询like提速优化
在使用msyql进行模糊查询的时候,很自然的会用到like语句,通常情况下,在数据量小的时候,不容易看出查询的效率,但在数据量达到百万级,千万级的时候,查询的效率就很容易显现出来.这个时候查询的效率就 ...
- 解救小哈——DFS算法举例
一.问题引入 有一天,小哈一个人去玩迷宫.但是方向感不好的小哈很快就迷路了.小哼得知后便去解救无助的小哈.此时的小哼已经弄清楚了迷宫的地图,现在小哼要以最快的速度去解救小哈.那么,问题来了... 二. ...
- CentOS 7 之前好好的,突然一天启动时黑屏,没有登陆界面了(配置 network-scripts 连网)
原因: 百度大神说是Gnome(一套纯粹自由的计算机软件,运行在操作系统上,提供图形桌面环境)不行了. 解决方法: 1. 重启系统,ctrl + alt + F2 进入命令行界面. 2. sudo s ...
- visual studio运行时库MT、MTd、MD、MDd 的区别
msdn上面的解释: MT:mutithread,多线程库,编译器会从运行时库里面选择多线程静态连接库来解释程序中的代码,即连接LIBCMT.lib库 MTd:mutithread+debug,多线程 ...