《编程之美》 2.19 区间重合判断

解法二的思路:

1 排序    O(N*logN)   (N为目标区间的个数)

2 合并    O(N)

3 二分查找 O(k*logN) (k为合并后区间的个数)

// 2.19.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct area
{
	int begin;
	int end;
};

bool compare(area& a,area& b)
{
	return a.begin<b.begin;
}
int _tmain(int argc, _TCHAR* argv[])
{
	int arr[] = {2, 5, 3, 4, 3, 9, 11, 15};
	vector<area> vec;
	area a;
	for(int i=0;i<sizeof(arr)/sizeof(arr[0]);)
	{
		a.begin=arr[i++];
		a.end=arr[i++];
		vec.push_back(a);
	}
	sort(vec.begin(),vec.end(),compare);//排序
//
	cout << "after sort: " << endl;

    for (int i = 0; i < vec.size(); i ++)

        cout << "(" << vec[i].begin << ", " << vec[i].end << ") ";

    cout << endl;
//

	//合并

	
	for(int i=1;i<vec.size();)
	{
		if(vec[i].begin<=vec[i-1].end && vec[i].end>=vec[i-1].end)
		{
			vec[i-1].end=vec[i].end;
			vec.erase(vec.begin()+i);
		}
		else if(vec[i].begin<=vec[i-1].end && vec[i].end<vec[i-1].end)
		{
			vec.erase(vec.begin()+i);
		}
		else
			++i;
	}
//

	cout << "after merger :" << endl;

    for (int i = 0; i < vec.size(); i ++)

        cout << "(" << vec[i].begin << ", " << vec[i].end << ") ";

    cout << endl;
	
	//二分查找

	area target;//设置源区间
	target.begin=2;
	target.end=8;

	int first=0;
	int last=vec.size()-1;

	bool flag=false;

	while(first<=last)
	{
		int mid=(first+last)/2;
		if(vec[mid].begin<=target.begin&&vec[mid].end>=target.end)
		{
			flag=true;
			break;
		}
		else if(vec[mid].end<target.begin)
			first=mid+1;
		else if(vec[mid].begin>target.end)
			last=mid-1;
		else
			break;
		
	}
	if(flag) cout<<"true"<<endl;
	else cout<<"false"<<endl;

	return 0;
}

    原文作者:muweiyou
    原文地址: https://blog.csdn.net/willmu/article/details/7967029
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞