(数组)leetcode 88:Merge Sorted Array

水平有限,不足之处还望指正。

题目:

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1and nums2 are m and n respectively.

题意:

给出两个有序的数组nums1和nums2,合并nums2到nums1中并保持原有顺,已确保nums1有足够的空间。

解题思路:

这里给出升序合并。在nums1(从m+n-1递减)的尾部从后向前逐个插入nums1(从m-1递减)与nums2(从n-1递减)中较大的数。时间复杂度为O(m+n)

AC代码如下(含有main函数,VS2013中可直接运行):

#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
	//升序合并
	//首先确保nums1的大小至少等于m+n
	void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {

		int index = m + n - 1;
		int s1Index = m - 1;
		int s2Index = n - 1;
		//从后向前逐个插入nums1与nums2中较大的数
		while (s1Index>=0 && s2Index>=0)
		{
			nums1[index--] = nums2[s2Index] >= nums1[s1Index] ? nums2[s2Index--] : nums1[s1Index--];
		}
		while (s1Index>=0)
		{
			nums1[index--] = nums1[s1Index--];
		}
		while (s2Index >= 0)
		{
			nums1[index--] = nums2[s2Index--];
		}
	}
};
int main()
{
	vector<int> nums1 = { 1, 5, 7, 9 };
	vector<int> nums2 = { 2, 4, 6, 8, 10 };

	Solution my_solution;
	
	int n = nums2.size();
	while (n > 0)
	{
		nums1.push_back(0);
		n--;
	}
	my_solution.merge(nums1, nums1.size()-nums2.size(), nums2, nums2.size());

	for (int i = 0; i < nums1.size(); i++)
		cout << nums1[i] << " ";
	cout << endl;

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值