Solution using PriorityQueue


  • 0
    W
    List<Interval> ans = new ArrayList<>();
            PriorityQueue<Interval> queue = new PriorityQueue<>(new Comparator<Interval>() {
                @Override
                public int compare(Interval o1, Interval o2) {
                    if (o1.start < o2.start) {
                        return -1;
                    } else if (o1.start == o2.start) {
                        return 0;
                    } else {
                        return 1;
                    }
                }
            });
            for (Interval elem : intervals) {
                if (elem != null) {
                    queue.add(elem);
                }
            }
    
            while (!queue.isEmpty()) {
                if (queue.size() == 1) {
                    ans.add(queue.poll());
                    break;
                } else {
                    Interval first = queue.poll();
                    Interval second = queue.poll();
                    if (first.end >= second.start) {
                        queue.add(new Interval(first.start, Math.max(first.end, second.end)));
                    } else if (first.end < second.start) {
                        ans.add(first);
                        queue.add(second);
                    }
                }
            }
    
            return ans;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.