您的位置:首页 > 编程语言 > C语言/C++

LeetCode_Merge Sorted Array

2015-05-14 11:24 323 查看

一.题目


Merge Sorted Array

  Total Accepted: 52295 Total Submissions: 173663My
Submissions

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.

Show Tags

Have you met this question in a real interview?  

Yes
 

No

Discuss







二.解题技巧

    这道题是一道比较水的题,没有很复杂的算法,只是一个技巧问题。如果单纯得考虑从小到大地将两个数组进行合并的话,每次在num1中插入一个数的话,需要将后面的元素都向后移动一位,这样,整个处理过程的时间复杂度为O(m*n)。
    由于两个数组的元素的个数是知道的,同时,合并后的数组也是递增排序的,也就是说,排序之后的数组的最大值是放在最后面的,因此,我们可以从后往前遍历,也就是将最大值放在第一个数组的m+n-1位置,然后将次最大值放在m+n-2位置,依次类推,这样在将元素放置到合适位置的时候,就不需要移动元素,这个方法的时间复杂度为O(m+n)。

三.实现代码

#include <iostream>
#include <vector>

using std::vector;

class Solution
{
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
int ResultIndex = m + n - 1;
m--;
n--;
while (m >= 0 || n >= 0)
{
if (m < 0)
{
nums1[ResultIndex--] = nums2[n--];
continue;
}

if (n < 0)
{
nums1[ResultIndex--] = nums1[m--];
continue;
}

if (m >= 0 && n >= 0)
{
if (nums1[m] > nums2
)
{
nums1[ResultIndex--] = nums1[m--];
continue;
}
else
{
nums1[ResultIndex--] = nums2[n--];
continue;
}
}
}

}
};


四.体会

    这道题只是一个技巧问题,有时从前往后进行处理的时候不太好操作的话,可以考虑从后往前处理。

版权所有,欢迎转载,转载请注明出处,谢谢

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ algorithm leetcode merge