合并有序区间

http://haixiaoyang.wordpress.com/category/intervalsegment/

//None overlap segments (5,10)(15,17)(18,25), 
//insert (16,35), print out merged result:(5,10)(15,35)

void PrintMergRes(int a[], int b[], int n, int nBeg, int nEnd)
{
	assert(a && b && n > 0 && nBeg < nEnd);

	int i = 0;
	bool bPrinted = false;
	while (i < n)
	{
		if (a[i] > nEnd && !bPrinted)
		{
			cout<<"("<<nBeg<<" "<<nEnd<<")"<<endl;
			bPrinted = true;
		}
		else
		{
			if (max(nBeg, a[i]) <= min(nEnd, b[i]))
			{
				nBeg = min(nBeg, a[i]);
				nEnd = max(nEnd, b[i]);
			}
			else 
				cout<<"("<<a[i]<<" "<<b[i]<<")"<<endl;
			i++;
		}
	}

	//falls after all intervals
	if (!bPrinted) 
		cout<<"("<<nBeg<<" "<<nEnd<<")"<<endl;
}


看似很简单的题目,但是要优美正确的写出来,还是需要一定功夫的


/*
Given two arrays storing ranges(none overlap), output their intersection.
Input:
A: [1,5], [8,15], [30,90]
B: [2,7], [12,18], [80,100]
Output:
[2,5], [12,15], [80,90]
*/

struct RANGE
{
	int nBeg;
	int nEnd;
};

void PrintIntersect(RANGE rg1[], int n1, RANGE rg2[], int n2)
{
	assert(rg1 && rg2 && n1 > 0 && n2 > 0);

	//Typical merge sort logic without a think
	int nIter1 = 0;
	int nIter2 = 0;
	while (nIter1 < n1 && nIter2 < n2)
	{
		//This logic below is the way to judge whether two segment
		//intersect with each other. Double think why!!
		int nMaxBeg = max(rg1[nIter1].nBeg, rg2[nIter2].nBeg);
		int nMinEnd = min(rg1[nIter1].nEnd, rg2[nIter2].nEnd);
		if (nMinEnd >= nMaxBeg)
			cout<<nMaxBeg<<" "<<nMinEnd<<endl;

		if (rg1[nIter1].nEnd <= rg2[nIter2].nEnd)
			nIter1++;
		else nIter2++;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值