[Lintcode]3Sum

来源:互联网 发布:神硕微信免费推广软件 编辑:程序博客网 时间:2024/04/30 05:30

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

这道题貌似没有什么简单算法,所以直接三重循环,三个指针,遍历所有可能性。记得提前排序和pass掉重复元素。

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) {        Arrays.sort(numbers);        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();                for(int right = numbers.length - 1; right > 1; right--) {            for(int left = 0; left < right - 1; left++) {                for(int i = left + 1; i < right; i++) {                    if(numbers[left] + numbers[right] + numbers[i] == 0) {                        ArrayList<Integer> tmp = new ArrayList<Integer>();                        tmp.add(numbers[left]);                        tmp.add(numbers[i]);                        tmp.add(numbers[right]);                        res.add(tmp);                        break;                    }                }                while(left + 1 < right && numbers[left] == numbers[left + 1]) left++;            }            while(right - 1 > 0 && numbers[right] == numbers[right - 1]) right--;        }        return res;    }}


0 0
原创粉丝点击