Java [leetcode 15] 3Sum

來源:互聯網
上載者: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.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, abc)
  • 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)

解題思路

對於這樣的無序數組首先進行升序排列,使之變成非遞減數組,調用java內建的Arrays.sort()方法即可。

然後每次固定最小的那個數,在後面的數組中找出另外兩個數之和為該數的相反數即可。

具體的過程可參考部落格:http://blog.csdn.net/zhouworld16/article/details/16917071

代碼實現:

public class Solution {    List<List<Integer>> ans = new ArrayList<List<Integer>>();    public List<List<Integer>> threeSum(int[] nums) {        int length = nums.length;        if (nums == null || length < 3)            return ans;        Arrays.sort(nums);        for (int i = 0; i < length - 2; ++i) {            if (i > 0 && nums[i] == nums[i - 1])                continue;            findTwoSum(nums, i + 1, length - 1, nums[i]);        }        return ans;    }    public void findTwoSum(int[] num, int begin, int end, int target) {        while (begin < end) {            if (num[begin] + num[end] + target == 0) {                List<Integer> list = new ArrayList<Integer>();                list.add(target);                list.add(num[begin]);                list.add(num[end]);                ans.add(list);                while (begin < end && num[begin + 1] == num[begin])                    begin++;                begin++;                while (begin < end && num[end - 1] == num[end])                    end--;                end--;            } else if (num[begin] + num[end] + target > 0)                end--;            else                begin++;        }    }}

 

Java [leetcode 15] 3Sum

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.