Advertisement
Guest User

Untitled

a guest
Jan 27th, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. /**
  2. * Definition for an interval.
  3. * public class Interval {
  4. * int start;
  5. * int end;
  6. * Interval() { start = 0; end = 0; }
  7. * Interval(int s, int e) { start = s; end = e; }
  8. * }
  9. */
  10. /*
  11. * Thought:
  12. * 1. sort the list by the start
  13. * 2. compare two Interval, the firstInterval.end > secondInterval.start merge these two Intervals
  14. * 3. the mergedInterval{ start = firstInterval.start, end = Math.max(firstInterval.end, secondInterval.end)}
  15. */
  16. public class Solution {
  17. public List<Interval> merge(List<Interval> intervals) {
  18. List<Interval> resultLst = new ArrayList<Interval>();
  19. Interval lastIntval;
  20. if(intervals.size() == 0)
  21. return resultLst;
  22. Collections.sort(intervals, new Comparator<Interval>() {
  23. public int compare(Interval a, Interval b) {
  24. return a.start - b.start;
  25. }
  26. });
  27. lastIntval = intervals.get(0);
  28. for(int i = 0; i < intervals.size(); i++) {
  29. Interval curr = intervals.get(i);
  30. if(lastIntval.end < curr.start) {
  31. resultLst.add(lastIntval);
  32. lastIntval = curr;
  33. } else {
  34. //merge the two intervals
  35. lastIntval.end = Math.max(lastIntval.end, curr.end);
  36. }
  37. }
  38. resultLst.add(lastIntval);
  39. return resultLst;
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement