【小米OJ-三元组】集合中有集合

 

 

 

package lianxi;
import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        String line;
        while (scan.hasNextLine()) {
            line = scan.nextLine().trim();
            // please write your code here
            String str[] = line.split(",");
            int arr[] = new int[str.length];
            for(int i=0;i<arr.length;i++) arr[i] = Integer.parseInt(str[i]);
            System.out.println(Main.threeSum(arr).size());
        }
    }
    private static List<List<Integer>> threeSum(int []num){
       List<List<Integer>> ans = new ArrayList<List<Integer>>();
       int len = num.length;
       if(len<3) return ans;///不是三元组;
        Arrays.sort(num);
        for(int i=0;i<len;i++){
            if(num[i]>0) break;///大于0表示当前数列没有小于0的数,所以没有三元组

            if(i>0&&num[i]==num[i-1]) continue;
            int begin = i+1;
            int end = len-1;
            while(begin<end){
                int sum = num[i]+num[begin]+num[end];
                if(sum==0){
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(num[i]);
                    list.add(num[begin]);
                    list.add(num[end]);
                    ans.add(list);///当前容器存下种数
                    begin++;
                    end--;
                    while(begin<end&&num[begin]==num[begin-1]) begin++;
                    while(begin<end&&num[end]==num[end+1]) end--;
                }else if(sum>0) end--;///当前和比较大,所以缩小最大范围
                else begin++;///当前和小,增大最小范围
            }
        }
        return ans;
    }
} 
posted @ 2020-04-29 18:00  wusheng_z  阅读(192)  评论(0编辑  收藏  举报