题解 | 合并区间

合并区间

https://www.nowcoder.com/practice/69f4e5b7ad284a478777cb2a17fb5e6a

import java.util.*;

import java.util.stream.Collectors;

/*
 * public class Interval {
 *   int start;
 *   int end;
 *   public Interval(int start, int end) {
 *     this.start = start;
 *     this.end = end;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param intervals Interval类ArrayList
     * @return Interval类ArrayList
     */
    public ArrayList<Interval> merge (ArrayList<Interval> intervals) {
        // write code here
        // console.log(intervals)]]

        ArrayList<Interval> ans = new ArrayList<Interval>();
        if (intervals.size() == 0) return ans;
        
        //  排序
        // Collections.sort(intervals, new Comparator<Interval>() {
        //     public int compare(Interval o1, Interval o2) {
        //         if (o1.start != o2.start) {
        //             return o1.start - o2.start;
        //         } else {
        //             return o1.end - o2.end;
        //         }
        //     }
        // });
        List<Interval> its = intervals.stream().sorted(new Comparator<Interval>() {
            public int compare(Interval o1, Interval o2) {
                if (o1.start != o2.start) {
                    // System.out.println("www");
                    return o1.start - o2.start;
                }

                else {
                    // System.out.println("xxx");
                    return o1.end - o2.end;
                }
                    
            }
        }).collect(Collectors.toList());
        // its.forEach(i ->System.out.println(i.start + " /" + i.end));
        ans.add((its.get(0)));
        int count = 0;
        for (int i = 1; i < its.size(); i++) {
            Interval o1 = its.get((i));
            Interval origin = ans.get(count);
            if (o1.start > origin.end) {
                ans.add(o1);
                count++;
            } else {
                ans.remove(count);
                Interval s = new Interval(origin.start, o1.end);
                if (o1.end < origin.end) s.end = origin.end;
                ans.add(s);
            }
        }
        return ans;
    }

}

全部评论

相关推荐

Lorn的意义:你这种岗位在中国现在要么牛马天天加班,要么关系户进去好吃好喝,8年时间,真的天翻地覆了,对于资本来说你就说一头体力更好的牛马,哎,退伍没有包分配你真的亏了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务