Advertisement
1988coder

986. Interval List Intersections

Mar 1st, 2019
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/interval-list-intersections/
  3. import java.util.ArrayList;
  4.  
  5. // Definition for an interval.
  6. class Interval {
  7.     int start;
  8.     int end;
  9.  
  10.     Interval() {
  11.         start = 0;
  12.         end = 0;
  13.     }
  14.  
  15.     Interval(int s, int e) {
  16.         start = s;
  17.         end = e;
  18.     }
  19. }
  20.  
  21. /**
  22.  * Using modified Merge operation of Morge Sort
  23.  *
  24.  * Refer:
  25.  * https://leetcode.com/problems/interval-list-intersections/discuss/231108/C++-O(n)-"merge-sort"
  26.  *
  27.  * Time Complexity: O(A + B)
  28.  *
  29.  * Space Complexity: O(A + B)
  30.  *
  31.  * A = Length of array A. B = Length of array B.
  32.  */
  33. class Solution {
  34.     public Interval[] intervalIntersection(Interval[] A, Interval[] B) {
  35.         if (A == null || B == null || A.length == 0 || B.length == 0) {
  36.             return new Interval[0];
  37.         }
  38.  
  39.         ArrayList<Interval> result = new ArrayList<>();
  40.         int i = 0;
  41.         int j = 0;
  42.  
  43.         while (i < A.length && j < B.length) {
  44.             if (A[i].end < B[j].start) {
  45.                 i++;
  46.             } else if (B[j].end < A[i].start) {
  47.                 j++;
  48.             } else {
  49.                 result.add(new Interval(Math.max(A[i].start, B[j].start), Math.min(A[i].end, B[j].end)));
  50.                 if (A[i].end < B[j].end) {
  51.                     i++;
  52.                 } else {
  53.                     j++;
  54.                 }
  55.             }
  56.         }
  57.  
  58.         return result.toArray(new Interval[result.size()]);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement