【数组】合并有序数列

题目:有两个有序的数组string1和string2,写一个函数,将string2插入到string1中,并且string1仍是有序的数组。


输入:两个有序数组

输出:合并后一个有序数组


需要考虑的细节:

1、数组string1是否有足够的空间容纳string2;

在程序中,需要考虑到两个数组的长度不能大于string1的实际长度。

2、是否能够只遍历一次数组,复杂度O(n);

直接的做法是,正序遍历string1和string2,将string2中的数字插入到string1合适的位置。每插入一个数字,string1被插入位置的后面所有数字都后移一位,复杂度OO(n^2)。换一种思路,如果一开始每个数字所放的位置就是空闲的,不需要其他数字让位置,这样就能实现复杂度O(n)。由此想到,逆序遍历string1和string2,正好可以实现。


代码如下:

void mergeSortedString(int str1[], int len1, int str2[], int len2, int length)
{
    if(str1 == NULL || str2 == NULL || len1 <= 0 || len2 <= 0 || length <=0)
    {
        return;
    }

	int newLength = len1 + len2;
	if (newLength > length)
	{
		return;
	}
	
    int newIndex1 = newLength - 1;
    int index1 = len1 - 1;
    int index2 = len2 - 1;

    while (newIndex1 >= 0 && index1 >= 0 && index2 >= 0)
    {
        if (str1[index1] > str2[index2])
        {
            str1[newIndex1--] = str1[index1--];
        }
        else
        {
            str1[newIndex1--] = str2[index2--];
        }
    }
	
	while (index1 >= 0)
	{
		str1[newIndex1--] = str1[index1--];
	}
	
	while (index2 >= 0)
	{
		str1[newIndex1--] = str2[index2--];
	}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值