A really strange bug in my compare function for sort(), Can someone help?


  • 0
    B

    The idea is simple. I sort the array intervals according to intervals[i].start, Then it's easy to finish it.
    But I met a really strange problem. I write a compare function for sort:

    static bool myfunction(Interval i, Interval j){
        return (i.start < j.start);
    }
    

    This function can work, but if I do a little change,like this:

    static bool myfunction(Interval i, Interval j){
        return (i.start <= j.start);
    }
    

    Then I got a Run Time Error. I find the result of sort() is wrong. Can anyone help me?

    Following is my AC code:

    class Solution{
    public:
    static bool myfunction(Interval i, Interval j){
    //If I write it in this way: return i.start <= j.start , it can't pass.
        return (i.start < j.start);
    }
    
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> res;
        if (intervals.empty()){
            return res;
        }
        sort(intervals.begin(), intervals.end(), myfunction);
        Interval node = intervals[0];
        for (int i = 1; i < intervals.size(); ++i){
            if (intervals[i].start <= node.end){
                node.end = max(intervals[i].end, node.end);
            }
            else {
                res.push_back(node);
                node = intervals[i];
            }
        }
        res.push_back(node);
        return res;
    }
    };

Log in to reply
 

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