现在的位置: 首页 > 综合 > 正文

[排序数组合并]

2018年04月12日 ⁄ 综合 ⁄ 共 495字 ⁄ 字号 评论关闭

在leetcode上也有的,从后面合并就好了。

只是以前的代码风格不如这个好,尤其是链表合并的时候也是。

修改一下,但是在比较的时候犯了个错误,就是如果要用

if ( p1>=0 )
{
small=max(small,arr1[p1]);
sIdx=&p1;
}

这样肯定是不行的,因为每次比较都会修改sIdx,这样不对,而是只有 它比small大的时候才修改。

记住这个错误。

void mergeSortedArray(int arr1[], int arr2[], int n, int m) {
	int p1=n-1,p2=m-1;
	int p3=n+m-1;
	if ( !arr1 || !arr2 )
		return;
    const int INT_MIN =  -10000000;
	while( p1>=0 || p2 >=0 )
	{
		int small=INT_MIN;
		int *sIdx=NULL;
		if ( p1>=0 && arr1[p1]>=small)
		{
			small=arr1[p1];
			sIdx=&p1;
		}
		if ( p2>=0 && arr2[p2] >= small)
		{
			small=arr2[p2];
			sIdx=&p2;
		}
		arr1[p3--]=small;
		*sIdx=*sIdx-1;
	}
}

抱歉!评论已关闭.