O(1)space, no need to re-create a new List for result


  • 0
    D

    '''

    public class Solution {

    public List<Interval> merge(List<Interval> intervals) {
        if (intervals == null || intervals.size() == 0) {
            return intervals;
        }
        Collections.sort(intervals, new Comparator<Interval>(){
            public int compare(Interval a, Interval b) {
                return a.start - b.start;
            }
        });
        Interval pre = intervals.get(0);
        int index = 0;
        for (int i = 1; i < intervals.size(); i++) {
            Interval cur = intervals.get(i);
            if (cur.start > pre.end) {
    
                intervals.set(index++, pre);
                pre = cur;
            } else {
                pre.start = Math.min(pre.start, cur.start);
                pre.end = Math.max(pre.end, cur.end);
            }
        }
        intervals.set(index, pre);
        int size = intervals.size();
        for (int i = 0; i < size - index - 1; i++) {
            intervals.remove(intervals.size() - 1);
        }
        return intervals;
    }
    

    }
    '''
    '''


  • 0
    Z
    for (int i = 0; i < size - index - 1; i++) {
        intervals.remove(intervals.size() - 1);
    }
    

    List's remove method is not O(1), so this boost your running time to O(n^2). Not sure that's a good tradeup for O(1) space.


Log in to reply
 

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