88. Merge Sorted Array

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

解析

  • 最优解:从后往前处理,不需要开辟额外空间
class Solution_88 {
public:
    // merge nums2 into nums1 as one sorted array.
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {

        if (m==0)
        {
            for (int i = 0; i < n;i++)
            {
                nums1.push_back(nums2[i]);
            }
            return;
        }
        if (n==0)
        {
            return;
        }
        int len1 = m - 1;
        int len2 = n - 1;
        int index = m + n - 1;
        while (len1>=0&&len2>=0)
        {
            if (nums2[len2]>nums1[len1])
            {
                nums1[index--] = nums2[len2--];
            }
            else
            {
                nums1[index--] = nums1[len1--];
            }
        }

        while (len2>=0)
        {
            nums1[index--] = nums2[len2--];
        }

        return;
    }

    void merge(int A[], int m, int B[], int n) {
        int i = m - 1;
        int j = n - 1;
        int index = m + n - 1;

        while (i>=0&&j>=0)
        {
            A[index--] = (A[i] > B[j]) ? A[i--] : B[j--];
        }
        while (j>=0)
        {
            A[index--] = B[j--];
        }
        return;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8793434.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞