美文网首页
LeetCode 88. Merge Sorted Array

LeetCode 88. Merge Sorted Array

作者: cb_guo | 来源:发表于2019-02-25 19:50 被阅读0次

题目描述

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

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

Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]

题目思路

  • 看 discussion 得到的思路,真是优秀,从后往前,倒叙插入,真是绝妙,

代码 C++

  • 思路一、
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i = m-1;
        int j = n-1;
        int k = m+n-1;
        
        while(i >= 0 && j >= 0){
            if(nums1[i] > nums2[j]){
                nums1[k--] = nums1[i--];
            }
            else{
                nums1[k--] = nums2[j--];
            }
        }
        // j>=0 证明 nums2 中还有数据没有插入 nums1 中,下面两行代码为将nums2中剩余的代码放入nums1中
        // 至于为何没考虑 nums1 是因为,若 i>= 0 则 nums1 中数据本身还在nums1 中,不需要动,
        // 本题为将nums2 中数据插入nums1中,并且为倒着插入
        while(j >= 0){
            nums1[k--] = nums2[j--];
        }
    }
};

总结展望

相关文章

网友评论

      本文标题:LeetCode 88. Merge Sorted Array

      本文链接:https://www.haomeiwen.com/subject/njcnyqtx.html