LeetCode Problem Link

https://leetcode.com/problems/merge-sorted-array

Intuition

  • make the little copy as possible
  • shift nums1 to secure the fronted space? no!
  • visit from the back!

Approach

  • to avoid runtime error, check index before it is used.
  • with the if cases, I could come up with all the corner cases.
  • lastly, if the k is from i and j, then just check i and j before use them.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


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;
        if (k<0) {
            return;
        }
        while (i>=0 && j>=0) {
            if (nums1[i] > nums2[j]) {
                nums1[k--] = nums1[i--];
            }
            else {
                nums1[k--] = nums2[j--];
            }
        }

        while (j>=0) {
            nums1[k--] = nums2[j--];
        }
    }

    void merge_v1(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i=m-1;
        int j=n-1;
        int k=m+n-1;
        if (k<0) {
            return;
        }
        if (i<0) {
            for (;k>=0&&j>=0;k--,j--) {
                nums1[k] = nums2[j];
            }
            return;
        }
        if (j<0) {
            for (;k>=0&&i>=0;k--,i--) {
                nums1[k] = nums1[i];
            }
            return;
        }

        while (k>=0) {
            if (i<0 && j>=0) {
                nums1[k--] = nums2[j--];
                continue;
            }
            if (j<0 && i>=0) {
                nums1[k--] = nums1[i--];
                continue;
            }
            if (nums1[i] > nums2[j]) {
                nums1[k--] = nums1[i--];
            }
            else {
                nums1[k--] = nums2[j--];
            }
        }
    }
};

GitHub

merge-sorted-array