【leetcode】3SUM
来源:互联网 发布:独立域名和二级域名 编辑:程序博客网 时间:2024/06/05 03:55
题目:
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)解题思路:
将3sum问题转化为2sum问题,用O(n)时间遍历数组,对于每个元素num[i],找到2sum之和为-num[i]的元素,2sum时间复杂度可以为O(n*lgn),因为排序只需要一次,所以3sum的时间复杂度为O(n^2) + O(n*lgn)=O(n^2)。或者借助hashmap,时间复杂度依然是O(n^2)。
代码:
import java.util.ArrayList;import java.util.Arrays;public class Solution {private ArrayList<ArrayList<Integer>> list; public ArrayList<ArrayList<Integer>> threeSum(int[] num) {list = new ArrayList<ArrayList<Integer>>();Arrays.sort(num);for (int i = 0; i <= num.length - 3; i++) {if (i != 0 && num[i] == num[i - 1]) {continue;}twoSum(num, i, i + 1, num.length - 1);}return list;}private void twoSum(int[] num, int i, int begin, int end) {while (begin < end) {int sum = num[begin] + num[end];if (sum == -num[i]) {ArrayList<Integer> tmpList = new ArrayList<Integer>();tmpList.add(num[i]);tmpList.add(num[begin]);tmpList.add(num[end]);list.add(tmpList);begin++;end--;while (begin < end && num[begin] == num[begin - 1]) {begin++;}while (begin < end && num[end] == num[end + 1]) {end--;}}else if (sum < -num[i]) {begin++;} else if (sum > -num[i]){end--;}}}public static void main(String[] args) {int num[] = {-1,0,1,2,-1,-4};System.out.println(new Solution().threeSum(num));}}
0 0
- 【Leetcode】3Sum (Sum)
- Leetcode:2Sum,3Sum
- 【Leetcode】3Sum Closest (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 3Sum
- LeetCode: 3 Sum Closest
- leetcode - 3 Sum
- leetcode - 3 sum closest
- leetcode 3Sum
- leetcode 3Sum Closest
- LeetCode: 3Sum
- Linux命令:SAR命令
- 小米3S或采用5.5寸1080p屏 配3G内存支持4G
- win32 010 使用masm32
- Android NDK开发简介 NDK和SDK以及JNI有什么关系?
- 【Using Infographics】使用信息图表
- 【leetcode】3SUM
- 【OpenCV】图像特征的提取以及相似性比较方法
- ajax使用时机
- 根据A、B两点经纬度计算距离
- Target runtime Apache Tomcat v7.0 is not defined. .
- OCP 1Z0 051 4
- 谄鹤兔废亲冠抵怖脱估跟我进来吧!”唐紫尘看了王超几眼,随后带着他进了别
- js数组操作常用方法 转自:http://www.jbxue.com/article/js/20224.html
- hadoop 启动的时候datanode报错 Problem connecting to server