1. 程式人生 > >Merge Intervals(LeetCode)

Merge Intervals(LeetCode)

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

//Definition of Interval:
class Interval {
public:
    int start, end;
    Interval(int start, int end) {
        this->start = start;
        this->end = end;
    }
};

class Solution
{
public:
	/**
	* @param intervals: interval list.
	* @return: A new interval list.
	*/
	vector<Interval> merge(vector<Interval> &intervals)
	{
		if (intervals.empty())
		{
			return intervals;
		}
		//mergeSort(intervals, 0, intervals.size()-1);
		sort(intervals.begin(), intervals.end(), myfun);
		/*cout << "------sort -----------" << endl;
		display(intervals);*/
		vector<Interval> result;
		Interval temp = intervals[0];
		
		for (int i = 1; i < intervals.size(); i++)
		{
			if (temp.end >= intervals[i].start)
			{
				if (temp.end < intervals[i].end)
				{
					temp.end = intervals[i].end;
				}
			} else
			{
				result.push_back(temp);
				temp = intervals[i];
			}
		}
		result.push_back(temp);
		return result;
	}

	void display(vector<Interval> &nums)
	{
		for (int i = 0; i < nums.size(); i++)
		{
			cout << nums[i].start << " " << nums[i].end << endl;
		}
		return;
	}

private:
	static bool myfun(Interval t1, Interval t2)
	{
		return t1.start < t2.start;
	}
	void mergeSort(vector<Interval> &nums, int start, int end)
	{
		if (start >= end)
		{
			return;
		}
		int mid = (start + end) / 2;
		mergeSort(nums, start, mid);
		mergeSort(nums, mid + 1, end);
		mergeSortCore(nums, start, mid, mid+1, end);
		return;
	}

	void mergeSortCore(vector<Interval> &nums, int start, int end, int start2, int end2)
	{
		Interval t(0, 0);
		vector<Interval> temp;
		int i = start;
		while (start <= end && start2 <= end2)
		{
			if (nums[start].start > nums[start2].start)
			{
				temp.push_back(nums[start2++]);
			} else
			{
				temp.push_back(nums[start++]);
			}
		}
		while (start <= end)
		{
			temp.push_back(nums[start++]);
		}
		while (start2 <= end2)
		{
			temp.push_back(nums[start2++]);
		}
		for (int j = 0; j < temp.size() && i <= end2; j++,i++)
		{
			nums[i] = temp[j];
		}
		return;
	}

};

int main()
{
	int start[] = {74, 61, 46, 51, 50, 60};
	int end[] = { 78, 63, 50, 54, 50, 64 };
	vector<Interval> nums;
	Interval *temp;
	for (int i = 0; i < 6; i++)
	{
		temp = new Interval(start[i], end[i]);
		nums.push_back(*temp);
	}
	Solution st;
	st.display(nums);
	
	nums = st.merge(nums);
	cout << "---------result ---------------------" << endl;
	st.display(nums);
	return 0;
}