leetcode001:3sum solution
来源:互联网 发布:汉诺塔问题算法 编辑:程序博客网 时间:2024/05/20 01:37
leetcode网站,提供了一些算法题,还有内嵌了c++和java的编辑器,提供运行测试。
所以决定弥补自己算法的不足,多学习多思考实现。
第一道题就难倒我了= =||题目如下
3Sum
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)
o(n^2)的解决方案:
于是乎急急忙忙开始实现,结果一运行,出了不少bug,关键:去重未做足,后来搜了好多3sum都是c++实现版本,找到一个java的,却是o(n^3)的方案,但是从里面的去重中得到启示。于是乎,代码如下:
public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(num.length>=3){ bubbleSort(num); for(int i=0;i<num.length-2;i++){ int a = num[i]; if(i!=0&&a==num[i-1]){//i右移时的重复,ps:在这里开始还纠结i-1会有问题,这里注意短路逻辑判断 continue; } int k = i+1; int n = num.length-1; while(k<n){ int b = num[k]; /*if(i!=0&&a==b){//改后bug k++; continue; }*/ int c = num[n]; if(n!=num.length-1&&c==num[n+1]){ n--; continue; } if(b+a+c == 0){ ArrayList<Integer> al = new ArrayList<Integer>(); al.add(a); al.add(b); al.add(c); result.add(al); // System.out.println("["+a+","+b+","+c+"]"); n--; continue; }else if(a+b+c>0){ n--; }else{ k++; } } } } return result; }: //冒泡排序,不在算法思考范围 public void bubbleSort(int[] array){ if(array.length == 0)return ;for(int i=0;i<array.length-1;i++){//i是计数标记for(int j=0;j<array.length-i-1;j++){//注意终止条件的判断,冒泡的亮点在于从头到尾一对一对比较if(array[j]>array[j+1]){swap(array, j, j+1);}}}}public void swap(int[] array,int i,int j){int temp = array[i];array[i] = array[j];array[j] = temp;}}嗯,花了两个晚上睡前时间,准备好下一题。
- leetcode001:3sum solution
- leetcode001-2Sum,3Sum
- leetcode001:Two Sum
- leetcode001 Two Sum
- Two Sum - leetcode001
- leetcode001——Two Sum
- [LeetCode] 3Sum Solution
- [LeetCode] 3 Sum, Solution
- LeetCode001
- leetcode001
- [LeetCode] 3Sum Closest, Solution
- Lintcode57 3Sum solution 题解
- 3Sum | LeetCode O(N*N) Solution
- The Solution to LeetCode 15 3Sum
- Lintcode59 3Sum Closest solution 题解
- [LeetCode] 4Sum Solution
- [LeetCode] Combination Sum, Solution
- [LeetCode] Two Sum, Solution
- Log中出现You must supply a layout_width attribute的解决方法
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- 立体菜单、带箭头的菜单、带说明信息的菜单
- 门面(Facade)模式
- 实现内存检测工具
- leetcode001:3sum solution
- Android 处理图片( 图像二值化、锐化、转换格式)
- 用MyEclipse搭建SSH框架 Struts Spring Hibernate
- C++类模板实现数据结构——栈
- 十道海量数据处理面试题与十个方法大总结
- A SOAP Example in Java
- Android初级开发第六讲--Activity的布局
- 这么多技术我该怎么学
- C2. Party