If I write the comp function{return i1.start<=i2.start;} (not <) . The result will be runtime error. why?


  • 1
    X

    bool comp(const Interval& i1, const Interval& i2){
    return i1.start<=i2.start;
    }
    class Solution {
    public:

    vector<Interval> merge(vector<Interval> &intervals) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<Interval> re;
        int le = intervals.size(); 
        if(le==0)  return re;
        if(le==1)  return intervals;
        std::sort(intervals.begin(),intervals.end(),comp);
        
        for(int i=0; i<le;)
        {
            int ss=intervals[i].start;
            int ee = intervals[i].end;
            i++;
            while(i<le && intervals[i].start<=ee)
            {
               ee=intervals[i].end;
               i++;
            }
            Interval ans(ss, ee);
            re.push_back(ans);
        }
        return re;
    }
    

    };


  • 0

    please format your code properly. Select your code and click on the {} button.


  • 12
    P

    It will produce Runtime Error simply because you provide the sort() with a wrong comparator.

    1. A correct comparator should have determined behavior, i.e. return the same result on same input.
    2. The result should be transitive, i.e., if you return true for a<b and b<c, you should return true for a<c
    3. The result should not contain conflicts, e.g., if you return true for a<b, you should return false for b<a
    4. return false for both a<b and b<a will means that a == b.

    Violating the above rules and trying to pass an invalid comparator to sort() will result in undefined behavior, usually crash.

    Click me for further details.


Log in to reply
 

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