Created
November 4, 2015 08:53
-
-
Save dborovikov/f6281734dae5623e7bfd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.Collections; | |
| import java.util.Iterator; | |
| import java.util.List; | |
| public class MergeRangesJava { | |
| public static class Range { | |
| public final int start; | |
| public final int end; | |
| public Range(int start, int end) { | |
| this.start = start; | |
| this.end = end; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Range{" + | |
| "start=" + start + | |
| ", end=" + end + | |
| '}'; | |
| } | |
| } | |
| public static List<Range> merge(Range... ranges) { | |
| List<Range> sorted = Arrays.asList(ranges); | |
| sorted.sort((r1, r2) -> Integer.compare(r1.start, r2.start)); | |
| Iterator<Range> it = sorted.iterator(); | |
| if (it.hasNext()) { | |
| List<Range> result = new ArrayList<>(); | |
| Range current = it.next(); | |
| while (it.hasNext()) { | |
| Range next = it.next(); | |
| if (current.end >= next.start) { | |
| current = new Range(current.start, Math.max(current.end, next.end)); | |
| } else { | |
| result.add(current); | |
| current = next; | |
| } | |
| } | |
| result.add(current); | |
| return result; | |
| } else { | |
| return Collections.emptyList(); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| System.out.println(merge()); | |
| System.out.println(merge(new Range(1, 1))); | |
| System.out.println(merge(new Range(1, 1), new Range(1, 1))); | |
| System.out.println(merge(new Range(1, 2), new Range(2, 3))); | |
| System.out.println(merge(new Range(1, 5), new Range(2, 3), new Range(6, 7))); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment