码迷,mamicode.com
首页 > 其他好文 > 详细

leet_15

时间:2016-01-26 12:11:12      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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.

Note:

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

 

package com.mingxin.leetcode.leet_15;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2016/1/25.
 */
public class ThreeSum {
    public static void main(String[] args){
        int num[] = {-1, -20, -5, -7, 0, 1, 2, 7, 6, 10};
        List<List<Integer>> result = threeSum(num);
        for(List<Integer> item1:result){
            System.out.println("{" + item1.get(0) + ", " + item1.get(1) + ", " + item1.get(2) + "}");
        }
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(nums.length<3||nums == null){
            return new ArrayList<List<Integer>>();
        }

        Arrays.sort(nums);
        for(int i = 0; i <= nums.length-3; i++){
            if(i==0||nums[i]!=nums[i-1]){
                int low = i+1;
                int high = nums.length-1;
                while(low<high){
                    int sum = nums[i]+nums[low]+nums[high];
                    if(sum == 0){
                        ArrayList<Integer> unit = new ArrayList<Integer>();
                        unit.add(nums[i]);
                        unit.add(nums[low]);
                        unit.add(nums[high]);

                        res.add(unit);

                        low++;
                        high--;

                        while(low<high&&nums[low]==nums[low-1]){
                            low++;
                        }

                        while(low<high&&nums[high]==nums[high+1]){
                            high--;
                        }
                    }else if(sum > 0){
                        high --;
                    }
                    else{
                        low ++;
                    }

                }
            }
        }
        return res;
    }
}

  

leet_15

标签:

原文地址:http://www.cnblogs.com/kniught-ice/p/5159581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!