15. 3Sum
来源:互联网 发布:lable java 编辑:程序博客网 时间:2024/06/08 09:33
题 目:
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]]
思 路:
首先将输入的数字全部进行一次sort()排序,而后利用两个指针,i,j,i是从num[0]开始,j是从num[n-1]开始,依次对比,找到a+b+c=0的-c为target。
class Solution: global res res=[] def Sum3(self, num): for i in range(0, num.__len__()): if i > 0 and num[i] == num[i - 1]: pass sum2(num, res, i) return res def sum2(self, num, res, target): i = target + 1; j = num.__len__ - 1 while i < j: if num[target] + num[i] + num[j] < 0: i += 1 elif num[target] + num[i] + num[j] > 0: j -= 1 else: a = [] a.append(num[target]) a.append(num[i]) a.append(num[j]) res = a i += 1 j -= 1 while i < num.__len__ and num[i] == num[i - 1]: i += 1 while j >= 0 and num[j] == num[j + 1]: j -= 1
num=[]
n=int(input("请输入数组的长度:"))
请输入数组的长度:>? 5
for i in range(0, n):
temp = int(input("输入数字:"))
num.append(temp)
num.sort()
sl=Solution()
sl.Sum3(num)
0 0
- 15. 3Sum && 16 sum closet && 18 4sum
- 15. 3Sum 和 18. 4Sum
- 1. Two Sum&15. 3Sum
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- 15. 3Sum
- [leetcode] 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- leetcode 15. 3Sum
- CCF CSP 编程题目和解答-----试题名称:窗口-------201403-2
- DUBBO+ZK
- switch语句
- JavaScript基础
- angualrjs实现分页查询
- 15. 3Sum
- Android面试题整理-3
- 腾讯多元化战略特征
- javascript更换背景
- 人生的缓冲带
- sparkSQL用jdbc访问mysql
- 从一个小例子来看setInterval的使用
- HttpUtility.UrlDecode(),HttpUtility()escape()、encodeURI()、encodeURIComponent()区别详解以及相应的前台解码和.net后台解码
- Mongodb缓存的使用