3Sum
来源:互联网 发布:原生js ajax实例 编辑:程序博客网 时间:2024/06/08 05:09
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)
看到这道题似曾相识,想到了4sum的那个算法。于是就按照那个思路去实现了,然而太naive了,写了个时间复杂度为O(n3)的算法..O(n2)的晚上补充上。
先上O(n3)算法:
package leetcode;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ThreeSum {public static void main(String[] args) {ThreeSum three = new ThreeSum();int nums[] = { 1, 2, 3, 4, 5, 6, 7, 9 };int num03[] ={9,-4,-5,8,-5,7,5,-6,-4,-13,9,-10,-13,-6,2,-15,-13,-9,-4,-13,-9,-9,13,-13,-9,9,-15,1,0,-14,-8,-13,-11,-5,2,0,9,14,9,-9,8,-5,-12,10,-3,5,3,-1,12,14,1,10,12,-1,13,-12,-14,13,4,-7,6,4,-5,11,6,4,-12,0,3,4,-2,-3,7,1,14,-11,-8,2,-5,11,-7,3,6,-9,9,4,-14,10,-6,-2,-11,-14,-13,-9,4,0,11,-1,-15,-9,-12,-1,3,10,7,-5,6,6,12,8,2,-9,-4,-6,-11,-9,5,-10,-14,-15,3};int nums02[] = {};int target = 10;List<List<Integer>> res = three.threeSum(num03, 0);for (List<Integer> list : res) {for (Integer integer : list) {System.out.print(" " + integer);}System.out.println();}}public List<List<Integer>> threeSum(int [] nums){ return threeSum(nums, 0); }public List<List<Integer>> threeSum(int[] nums, int target) {Arrays.sort(nums);//还是要排序// 固定两边,中间的一次循环//int p1 = 0, p2 = nums.length - 1;List<List<Integer>> res = new ArrayList<List<Integer>>(); for(int i=0;i<nums.length-3;i++){ for(int j=nums.length-1;j>=2;j--){ //中间的移动 int k = i+1; while(k<j){ int tempres = nums[i]+nums[j]+nums[k]; if( tempres == target){ ArrayList<Integer> temp = new ArrayList<Integer>(); temp.add(nums[i]); temp.add(nums[k]); temp.add(nums[j]); if(!res.contains(temp)) res.add(temp); } k++; } } }return res;}}
觉得实现思路跟4sum是类似的,不过固定的是中间的那个数字,先给数组排序,从固定数字的左侧跟右侧扫,如果== target 左右侧各往中间靠近一位;如果小于target则小的一面,也就是左侧的指针向右移动一位;否则,右侧的指针向左移一位。
0 0
- Two Sum && 3 Sum
- 【Leetcode】3Sum (Sum)
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- leetcode 2 sum 3sum 4sum
- 2Sum 3Sum 4Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 3Sum
- 3SUM
- 3-sum
- 3Sum
- 3Sum
- 3Sum
- 3Sum
- Windows8.1优化,解决磁盘100%的问题
- 小胖说事33-----iOS给Lable字体添加行间距
- OC_数组
- 深度搜索的应用----有向图的连通性
- 为什么win7 64位的没有debug?cmd中找不到
- 3Sum
- ECMAScript 6新特性介绍
- EnvironmentError:mysql config not found
- 移动端尺寸基础知识
- 亲密性原则
- c++静态库与动态库的区别
- 03 JAVA 数组
- python reshape()函数ValueError: total size of new array must be unchanged
- 关于D:\adt-bundle-windows-x86_64-20140624\sdk的问题