leetcode 15. 3Sum
2016-05-04 11:48
288 查看
import java.util.Arrays; import java.util.ArrayList; import java.util.List; //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) public class Solution { public static void main(String[] args) { int[] a = {-1,0,1,2,-1,-4}; List<List<Integer>> result = threeSum(a); System.out.println(result); } public static List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Arrays.sort(nums); for(int i = 0;i<nums.length-2;i++){ //遍历数组 int j = i+1; int end = nums.length-1; if(i>0&&nums[i] == nums[i-1]){ continue; } while(j<end){ //从当前元素之后的两头寻找与其之和为0的两个元素 if(nums[i]+nums[j]+nums[end] == 0){ List<Integer> a = new ArrayList<Integer>(); a.add(nums[i]); a.add(nums[j]); a.add(nums[end]); result.add(a); while(nums[end-1] == nums[end]&&end>j){ //若有相同元素,则直接跳过 end--; } while(nums[j+1] == nums[j]&&j<end){ j++; } end--; j++; }else if(Math.abs(nums[i])<Math.abs(nums[j]+nums[end])){ //若相加不为0,则根据情况调整两端位置 end--; }else{ j++; } } } return result; // List<List<Integer>> result = new ArrayList<List<Integer>>(); //容易理解但是超时的做法 // Arrays.sort(nums); // for(int i = 0;i<nums.length-2;i++){ // if(i>0&&nums[i] == nums[i+1]){ // continue; // } // for(int j = i+1;j<nums.length-1;j++){ // if(j>1&&nums[j] == nums[j+1]){ // continue; // } // for(int k = j+1;k<nums.length;k++){ // if(nums[i]+nums[j]+nums[k] == 0){ // List<Integer> a = new ArrayList<Integer>(); // // a.add(nums[i]); // a.add(nums[j]); // a.add(nums[k]); // result.add(a); // break; // } // } // } // } // // for(int i = 0;i<result.size()-1;i++){ // if(result.get(i).equals(result.get(i+1))){ // result.remove(i+1); // } // } // return result; } }
相关文章推荐
- android打包so文件到apk
- ArcGIS教程:有关修改图表的基础知识
- 字符串处理------回文判断
- 利用POI抽取PPT中的图片并保存在文件中
- KNN与K-Means的区别
- jenkins---配置邮件
- 根据PDF模板从数据库中读取数据动态生成PDF文件。或者用ireport+jasperreports这种组合也可以...
- C# 判断字符为空的6种方法的效率实测对比
- MySQL导入含有中文字段(内容)CSV文件乱码解决方法
- 举例讲解C语言对归并排序算法的基础使用
- Javascript 初识Javascript
- 非等高cell,根据图片宽高,排布tableview
- Java 利用POI操作PPT
- js 实现map
- 查看手机分辨率
- Android中LayoutParams的用法
- 10000小时法则
- Unix网络编程 第四章 笔记
- iOS tableView分组
- Activity基础总结---注册、布局设置、隐藏标题、创建菜单、销毁活动