Can somebody help to deal with Runtime Error


  • 0
    H

    Here is my code:

    1. use qsort
    2. check if two intervals should be combined
    3. if combined, merge it the second
    4. finally add the last one

    I tested it in my PC and it worked fine but cannot get through with some long intervals.

    int cmp(const void*a, const void*b)
    {
    	Interval*p1 = (Interval*)a;
    	Interval*p2 = (Interval*)b;
    	if (p1->start <  p2->start) return -1;
    	else if (p1->start == p2->start) return 0;
    	else return 1;
    }
    bool check_if_intersection(const Interval& i1, const Interval& i2)
    {
    	if (((i1.start <= i2.start) && (i2.start <= i1.end))
    		|| ((i2.start <= i1.start) && (i1.start <= i2.end)))
    	{
    		return true;
    	}
    	return false;
    }
    void merge_two_intervals(const Interval& i1, Interval& i2)
    {
        i2.start = i1.start<i2.start? i1.start: i2.start;
    	i2.end = i1.end > i2.end? i1.end:i2.end;
    }
    class Solution {
    public:
    	vector<Interval> merge(vector<Interval> &intervals)
    	{
    		vector<Interval> vec_results;
    	    if(intervals.empty()) return vec_results;
    		qsort(&intervals[0], intervals.size(), sizeof(intervals[0]), cmp);
    		for (int i = 0, size = intervals.size(); i<size - 1; i++)
    		{
    			if (check_if_intersection(intervals[i], intervals[i + 1]))
    			{
    				merge_two_intervals(intervals[i], intervals[i + 1]);
    			}
    			else
    			{
    				vec_results.push_back(intervals[i]);
    			}
    		}
    		vec_results.push_back(intervals.back());
    		return vec_results;
    	}
    };

Log in to reply
 

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