Merge Sorted Array--LeetCode

来源:互联网 发布:文明 mac 编辑:程序博客网 时间:2024/06/05 17:18

1.题目

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 nums1 and nums2 are m and n respectively.

2.题意

合并升序数组到nums1中

3.分析

借助3个index,分别对应数组nums1,数组nums2,和结果数组
遍历nums1和nums2,将其中较大值放入结果数组即可

由于结果放在nums1中,所以只能从后往前扫描,
如果从前往后扫描可能会覆盖掉未检查的元素
时间复杂度为O(m+n),m和n分别是两个数组的长度,空间复杂度是O(1)

注意数组尾元素为nums1[m-1]而非nums1[m],不要从m开始遍历
循环的判断条件是idx1 >= 0 && idx2 >= 0而非idx1 > 0 && idx2 > 0
对应的数组名不要混淆,不要遗忘两边index--的操作

4.代码

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