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.
For example, given array S = {-1 0 1 2 -1 -4}
, A solution set is:
(-1, 0, 1)
(-1, -1, 2)
思路:先排序,然后逐个作为起点,再把后面的数从左右两边开始往中间搜索,如果和为0就加入结果,如果大于零,right向左移动,如果小于零,left向右移动。注意去掉重复的情况。
public class Solution { /** * @param numbers : Give an array numbers of n integer * @return : Find all unique triplets in the array which gives the sum of zero. */ public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) { // write your code here ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(numbers == null || numbers.length == 0) return result; Arrays.sort(numbers); for(int i = 0; i < numbers.length - 2; i++){ if(i > 0 && numbers[i] == numbers[i - 1]) continue; int left = i + 1; int right = numbers.length - 1; while(left < right){ if(numbers[i] + numbers[left] + numbers[right] == 0){ ArrayList<Integer> line = new ArrayList<Integer>(); line.add(numbers[i]); line.add(numbers[left]); line.add(numbers[right]); result.add(new ArrayList<Integer>(line)); left++; right--; while(left < right && numbers[left] == numbers[left - 1]) left++; while(left < right && numbers[right] == numbers[right + 1]) right--; } else if(numbers[i] + numbers[left] + numbers[right] < 0){ left++; } else{ right--; } } } return result; } }
时间: 2024-10-21 16:04:28