15. 3Sum
2016-03-23 20:31
351 查看
题目
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.
思路:排序后两端夹挤。
注意:避免添加重复triplet.
改进:跳过相邻重复数。
复杂度: O(n^2)。
Java:
Python:
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)
思路:排序后两端夹挤。
注意:避免添加重复triplet.
改进:跳过相邻重复数。
复杂度: O(n^2)。
Java:
public ArrayList<ArrayList<Integer>> threeSum(int[] num) { Arrays.sort(num); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(num.length<3) return result; for(int i=0;i<num.length-2;){ int b = i+1, e = num.length-1; while(b<e){ if(num[b]+num[e]+num[i]==0) { ArrayList <Integer> temp = new ArrayList <Integer>(); temp.add(num[i]);temp.add(num[b]);temp.add(num[e]); if(!result.contains(temp)) result.add(temp); b++;e--; while(b<(num.length-1) && num[b-1]==num[b]) b++; while(e>1 && num[e+1]==num[e]) e--; } else if(num[b]+num[e]+num[i]<0) b++; else e--; } i++; while(i<(num.length-2) && num[i-1]==num[i]) i++; } return result;
Python:
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ sorted_nums = sorted(nums) l = len(nums) result = [] for k in xrange(l-2): i,j = k+1,l-1 target = 0-sorted_nums[k] while i<j: if sorted_nums[i] + sorted_nums[j] == target: temp = [sorted_nums[k], sorted_nums[i], sorted_nums[j]] if temp not in result: result.append(temp) if sorted_nums[i] == sorted_nums[i+1]: i+=1 elif sorted_nums[j] == sorted_nums[j-1]: j-=1 else: i+=1;j-=1 elif sorted_nums[i] + sorted_nums[j] < target: i+=1 else: j-=1 return result
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解