"Leetcode" Merge intervals to sort by comparator

Source: Internet
Author: User

Topic link Merge Intervals

/** * Definition for an interval. * public class Interval {* int start; * int end; * Interval () {start = 0; end = 0;} * Interval (int s, I NT e) {start = s; end = e;} * Title: Leetcode The 56th merge intervals interval merges the set of the given interval, merging the overlapping parts of the adjacent intervals * idea: Now the set of this interval is sorted from large to small, After traversing if the end of the current collection is greater than the head of the next set, then there is a coincidence to merge, and continue to judge the size of the interval after merging with the next interval of the head of the relationship, and then into the interval of the answer, if the tail is greater than less than the next interval of the head is not coincident, the current interval is  public class Solution {public list<interval> merge (list<interval> intervals) {if (Intervals.size () = = 0 | |        Intervals.size () = = 1) return intervals; List<interval> answer = new arraylist<interval> ();//Note: The List is a virtual class that cannot be initialized directly, it is initialized with its subclasses, that is, if it is new list< Interval> error Collections.sort (intervals,new intervalcomparator ());//First set the input interval set Interval pre =        Intervals.get (0);        for (int i = 1;i < Intervals.size (); i++) {Interval Curr = Intervals.get (i);        if (Pre.end < Curr.start) {//interval without merging Answer.add (PRE); pre = Curr;        } else{Interval merge = new Interval (pre.start,pre.end>curr.end?pre.end:curr.end);        Pre = merge;        }} answer.add (pre);    return answer; }}class Intervalcomparator implements Comparator<interval>{public int compare (Interval A,interval b) {return A.start-b.start;}}


"Leetcode" Merge intervals to sort by comparator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.