首页 > 移动平台 > 详细

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

时间:2020-04-29 18:29:04      阅读:82      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

 

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

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

原文:https://www.cnblogs.com/wszhu/p/12803766.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!