What's wrong with my code? It keeps gives me wrong answer[2,5] for [[1,4], [2,5]]


  • 0
    R
    class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        if not intervals:
            return []
        intervals = sorted(intervals)
        res = []
        res.append(Interval(intervals[0].start, intervals[0].end))
        for i in range(1, len(intervals)):
            # starting in not None guaranteed
            prev = res[-1]
            cur = intervals[i]
            if prev.end < cur.start:
                res.append(Interval(cur.start, cur.end))
            else:
                # merge
                if prev.end >= cur.end:
                    continue
                else:
                    prev.end = cur.end
        return res
    

    This is my code. Very simple, not sure what's wrong. I run the example in my pycharm with the input, it gives me answer [1,5] instead of [2,5]... Do I miss something?


  • 0

    You use sorted(intervals), but Interval objects don't have proper comparison, so the order you get is somewhat random, which is of course bad.


  • 0
    R

    Thanks, you are right. It is random if I don't specify a comparator.


Log in to reply
 

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