题目

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]的更多相关文章

  1. 蜗牛慢慢爬 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 ...

  2. 蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]

    题目 The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows li ...

  3. 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]

    题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...

  4. 蜗牛慢慢爬 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 ...

  5. 蜗牛慢慢爬 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 ...

  6. 蜗牛慢慢爬 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 ...

  7. 蜗牛慢慢爬 LeetCode 36.Valid Sudoku [Difficulty: Medium]

    题目 Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  8. 蜗牛慢慢爬 LeetCode 8. String to Integer (atoi) [Difficulty: Medium]

    题目 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cas ...

  9. 蜗牛慢慢爬 LeetCode 3. Longest Substring Without Repeating Characters [Difficulty: Medium]

    题目 Given a string, find the length of the longest substring without repeating characters. Examples: ...

随机推荐

  1. JavaWeb基础—CSS学习小结

    重点记忆:四种结合方式 三种基本选择器 1.CSS:层叠样式表 相当于皮肤 提高了可维护性.样式与内容分离(注释格式/* */) 2.CSS与HTML结合的四种方式:内联式.嵌入式.外部式  1.每个 ...

  2. Oracle中用户解锁

    以hr 用户为例: SQL> alter user hr account unlock; ユーザーが変更されました. SQL> alter user hr identified by hr ...

  3. 洛谷 1938 [USACO09NOV]找工就业Job Hunt

    洛谷 1938  [USACO09NOV]找工就业Job Hunt 题目描述 Bessie is running out of money and is searching for jobs. Far ...

  4. MySQL中类型后面的数字含义

    形式:类型(m) 1.整数型的数值类型已经限制了取值范围,有符号整型和无符号整型都有,而M值并不代表可以存储的数值字符长度,它代表的是数据在显示时显示的最小长度,当存储的字符长度超过M值时,没有任何的 ...

  5. 图片转换成word 公式

    1 下载安装mathpix, 利用该软件将图片转换成LaTeX公式 2 参考此帖,将LaTeX公式转换成word公式 https://www.douban.com/note/648629593/ ht ...

  6. 原生android(一)

    一.移动APP的几种类型 1.Native APP:基于智能手机操作系统,并使用原生程序编写运行的应用程序,有IOS,Android,Windows Phone8等系统 2.Web APP:运行在智能 ...

  7. Ubuntu解压zip包中文乱码

    解决方法:通过unar 工具解压 步骤一: 安装unar: sudo apt-get install unrar 步骤二: 解压(以test.zip为例):unar test.zip 解压成功,乱码问 ...

  8. 详细介绍redis的集群功能,带你了解真正意义上的分布式

    Redis 集群是一个分布式(distributed).容错(fault-tolerant)的 Redis 实现, 集群可以使用的功能是普通单机 Redis 所能使用的功能的一个子集(subset). ...

  9. tf导出pb文件,以及如何使用pb文件

    先罗列出来代码,有时间再解释 from tensorflow.python.framework import graph_util import tensorflow as tf def export ...

  10. Ruby知识点二:类

    1.追查对象是否属于某个类时,使用is_a?方法  追查某个对象属于哪个类时,使用class方法 判断某个对象是否属于某个类时,使用instance_of?方法 判断类是否包含某个模块,使用inclu ...