蜗牛慢慢爬 LeetCode 15. 3Sum [Difficulty: Medium]
题目
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]
]
翻译
给定一个数组S,它包含n个整数,它是否存在3个元素a,b,c,满足a+b+c=0?找出所有满足条件的元素数组。
提示:a,b,c三个元素必须是升序排列(也就是满足a ≤ b ≤ c),最终的结果不能包含重复的元素数组。例如给定S为{-1 0 1 2 -1 -4},返回结果是(-1, 0, 1)和(-1, -1, 2)。
Hints
Related Topics: Array, Two Pointers
最容易想到的应该就是三重循环搞定 为了减少时间复杂度 自己原本是想到将最后一重循环用哈希表替换然后达到O(n^2)的效果 其中先排序可以减少很多麻烦
不过tag里面是有Two Pointers的 应该想到排序之后将二三重循环用两个指针夹逼 discuss中也是这么做的
代码
Java
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Array.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for(int i=0;i<nums.length-2;i++){
int lo = i+1; int hi = num.length-1; int sum = -nums[i];
while(lo<hi){
if(nums[lo]+nums[hi]==sum){
res.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
while(lo<hi && nums[lo]==nums[lo+1]) lo++;
while(lo<hi && nums[hi]==nums[hi-1]) hi--;
lo++;hi--;
}else if(nums[lo]+nums[hi]<sum){
lo++;
}else{
hi--;
}
}
}
return res;
}
}
Python
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
mymap = {}
result = []
for i in range(len(nums)):
if nums[i] not in mymap:
l = []
l.append(i)
mymap[nums[i]] = l
else:
mymap[nums[i]].append(i)
for i in range(0, len(nums)-2):
if nums[i]>0:
break
if i>0 and nums[i]==nums[i-1]:
continue
for j in range(i+1, len(nums)-1):
if j>i+1 and nums[j]==nums[j-1]:
continue
target = -nums[i]-nums[j]
if target<nums[j]:
break
mylist = []
if target in mymap:
mylist = mymap[target]
else:
continue
for integer in mylist:
if integer!=i and integer!=j:
res = [nums[i],nums[j],nums[integer]]
result.append(res)
break
return result
//better solution from discuss
class Solution(object):
def threeSum(self, 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 15. 3Sum [Difficulty: Medium]的更多相关文章
- 蜗牛慢慢爬 LeetCode 16. 3Sum Closest [Difficulty: Medium]
题目 Given an array S of n integers, find three integers in S such that the sum is closest to a given ...
- 蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]
题目 The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows li ...
- 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]
题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...
- 蜗牛慢慢爬 LeetCode 19. Remove Nth Node From End of List [Difficulty: Medium]
题目 Given a linked list, remove the nth node from the end of list and return its head. For example, G ...
- 蜗牛慢慢爬 LeetCode 11. Container With Most Water [Difficulty: Medium]
题目 Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai ...
- 蜗牛慢慢爬 LeetCode 5.Longest Palindromic Substring [Difficulty: Medium]
题目 Given a string s, find the longest palindromic substring in s. You may assume that the maximum le ...
- 蜗牛慢慢爬 LeetCode 36.Valid Sudoku [Difficulty: Medium]
题目 Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...
- 蜗牛慢慢爬 LeetCode 8. String to Integer (atoi) [Difficulty: Medium]
题目 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cas ...
- 蜗牛慢慢爬 LeetCode 3. Longest Substring Without Repeating Characters [Difficulty: Medium]
题目 Given a string, find the length of the longest substring without repeating characters. Examples: ...
随机推荐
- JavaEE笔记(五)
version 必须配置在id后面 缓存文件在映射文件后面 一级缓存:session回话级别 Session缓存的作用 (1)减少访问数据库的频率.应用程序从内存中读取持久化对象的速度显然比到数据库中 ...
- P3703 [SDOI2017]树点涂色
P3703 [SDOI2017]树点涂色 链接 分析: 首先对于询问,感觉是线段树维护dfs序,每个点记录到根的颜色个数.第二问差分,第三问区间取max. 那么考虑修改,每次将一个点的颜色变成和父节点 ...
- linux安装anaconda3
1,查看系统的版本 Uname –r 2,安装git 等依赖库 yum install git yum install zlib-devel bzip2-devel openssl-devel nc ...
- fortran shapefile学习
试图编写一个fortran程序,用以判断给定的点是否落在给定shapefile的范围内. 需要利用到FortranGIS库 ,而该库又依赖于Shapefile C Library 安装shapelib ...
- centos7安装vim以及在vim中显示中文
1.centos7安装vim yum -y install vim(简单粗暴安装方法) 2.在vim中显示中文不出现乱码 (1).vim ~/.vimrc (~/.vimrc为vim配置文件) (2) ...
- springboot 前后端分离开发 从零到整(四、更改密码操作)
前端发送更改密码请求,头部携带token,服务端拦截器拦截头部token并解析,根据token中的信息来查询用户信息.需要登录才能进行的操作是由自己定的,有些操作可以直接放行.具体实现是: 上一章写到 ...
- oracle数据库数据字典应用
oracle数据字典 数据字典是由oracle服务器创建和维护的一组只读的系统表.数据字典分为两类:一是基表,二是数据字典视图. 数据字典视图包括用户名.用户权限.对象名.约束和审计等信息,是通过运行 ...
- 通过python将xml文件转换成html文件
#数据类型的转换 def main(): maxwidth = 100 #用于规范字段的长度 print_start() count=0 while True: ...
- python的eval和json.loads(),json.dumps()
eval() 将字符串当成一个表达式去执行,可以想象成一个去字符串然后执行的操作. In [1]: s = '3*8' In [2]: eval(s) Out[2]: 24 eval()和json.l ...
- Netty源码分析第2章(NioEventLoop)---->第2节: NioEventLoopGroup之NioEventLoop的创建
Netty源码分析第二章: NioEventLoop 第二节: NioEventLoopGroup之NioEventLoop的创建 回到上一小节的MultithreadEventExecutorG ...