标签:leetcode
题意: 找出一个数组内和为0的三元组,元组不能重复public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> rs = new LinkedList<List<Integer>>(); if(num == null || num.length < 3) return rs;//不能返回null Arrays.sort(num); System.out.println(); //a + b + c ==0 final int target = 0; for(int a =0; a < num.length-2;){//先固定第一个数字 if(num[a] > target) return rs; int b = a + 1, c = num.length - 1; while (b < c){//对后面两个数据进行调整 int sum = num[a] + num[b] + num[c]; if(sum == target){ List<Integer> r = new LinkedList<Integer>(); r.add(num[a]); r.add(num[b]); r.add(num[c]); rs.add(r); b++; while (b<c && num[b] == num[b-1])b++;//防止重复数据 c--; while (b<c && num[c + 1] == num[c])c--; }else if(sum > target){ c--; }else { b++; } } a ++; while (a< num.length -2 && num[a-1] == num[a]) a++;//防止重复 } return rs; }
标签:leetcode
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44810745