剑指offer_合并俩个有序数组

题目:给定俩个有序的数组,将俩个数组合并到一个数组中,使得数组依然有序。

解题思路:用 i 和 j 标记俩个数组的开始位置,俩俩比较,将小的数插入到新数组中。当一个数组结束的时候,将另外一个数组插入到新数组中。

示例代码如下:

#include<iostream>
#include<vector>
using namespace std;

void MergeOrderArray(vector<int>& vec1, vector<int>& vec2)
{
	vector<int> vec;
	unsigned int i = 0;
	unsigned int j = 0;

	while (i < vec1.size() && j < vec2.size())
	{
		if (vec1[i] < vec2[j])
		{
			vec.push_back(vec1[i]);
			i++;
		}
		else
		{
			vec.push_back(vec2[j]);
			j++;
		}
	}

	while (i < vec1.size())
	{
		vec.push_back(vec1[i]);
		i++;
	}

	while (j < vec2.size())
	{
		vec.push_back(vec2[j]);
		j++;
	}

	vector<int>::iterator it = vec.begin();
	while (it != vec.end())
	{
		cout << *it << " ";
		it++;
	}
	cout << endl;
}

int main()
{
		vector<int> vec1;// 1  2  3  4
		for (int i = 0; i < 4; i++)
		{
			vec1.push_back(i + 1);
		}

		vector<int>::iterator it1 = vec1.begin();
		while (it1 != vec1.end())
		{
			cout << *it1 << " ";
			it1++;
		}
		cout << endl;

		vector<int> vec2;// 3  4  5  6
		int j = 3;
		while (j < 7)
		{
			vec2.push_back(j); 
			j++;
		}

		vector<int>::iterator it2 = vec2.begin();
		while (it2 != vec2.end())
		{
			cout << *it2 << " ";
			it2++;
		}
		cout << endl;
		
		MergeOrderArray(vec1, vec2);

		return 0;
}

测试结果如下;
VS2013环境下测试

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值