lintcode-medium-3 Sum

來源:互聯網
上載者:User

標籤:

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;    }}

 

lintcode-medium-3 Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.