LeetCode_Merge Sorted Array

一.题目

Merge Sorted Array

   Total Accepted: 52295  Total Submissions: 173663 My 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[n])
                {
                    nums1[ResultIndex--] = nums1[m--];
                    continue;
                }
                else
                {
                    nums1[ResultIndex--] = nums2[n--];
                    continue;
                }
            }
        }

    }
};




四.体会

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



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


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值