C++ Runtime Error Code Problem


  • 0
    V
    class Solution {
    public:
    	vector<Interval> merge(vector<Interval> &intervals) {
    		if (intervals.size() <= 1) return intervals;
    		sort(intervals.begin(), intervals.end(), cmp);
    		vector<Interval> ret(1, intervals[0]);
    		for (size_t i = 1; i < intervals.size(); ++i) {
    			if (intervals[i].start <= ret[ret.size() - 1].end) {
    				ret[ret.size() - 1] = merge(ret[ret.size() - 1], intervals[i]);
    			}
    			else {
    				ret.push_back(intervals[i]);
    			}
    		}
    		return ret;
    	}
    private:
    	static bool cmp(const Interval &a, const Interval &b) {
    		return a.start < b.start ? 1 : (a.end < b.end);
    	}
    	Interval merge(const Interval &a, const Interval &b) {
    		return Interval(a.start, max(a.end, b.end));
    	}
    };
    

    The above code is runtime error.

    When I change the cmp function to follows, got Accepted.

    I don't know why... If someone knows, please tell me about that.

    static bool cmp(const Interval &a, const Interval &b) {
    	return a.start < b.start;
    }

  • 0
    I
    class Solution { public:
        vector<Interval> merge(vector<Interval> &intervals) {
            if (intervals.size() <= 1) return intervals;
            sort(intervals.begin(), intervals.end(), cmp);
            vector<Interval> ret(1, intervals[0]);
            for (size_t i = 1; i < intervals.size(); ++i) {
                if (intervals[i].start <= ret[ret.size() - 1].end) {
                    ret[ret.size() - 1] = merge(ret[ret.size() - 1], intervals[i]);
                }
                else {
                    ret.push_back(intervals[i]);
                }
            }
            return ret;
        } private:
        static bool cmp(const Interval &a, const Interval &b) {
            if(a.start < b.start) return 1;
            else if(a.start > b.start) return 0;
            else if(a.end < b.end) return 1;
            else if(a.end > b.end) return 0;
            return 0;
        }
        Interval merge(const Interval &a, const Interval &b) {
            return Interval(a.start, max(a.end, b.end));
        } };

  • 0
    V

    but why "return a.start < b.start ? 1 : (a.end < b.end);" will get runtime error?


  • 0
    I

    if a.start > b.start and a.end < b.end, result should be false, but your code get true


Log in to reply
 

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