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

  • 1

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

    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;
        for(int i=0; i<le;)
            int ss=intervals[i].start;
            int ee = intervals[i].end;
            while(i<le && intervals[i].start<=ee)
            Interval ans(ss, ee);
        return re;


  • 0

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

  • 12

    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.