Thanks the top post from @leetchunhui

  • 0

    First solving this problem , we all think in the from left to right order. But we face the problem that if we

    insert the elements from nums2 to nums1 , then we have to move the related elements in nums1 afterwards.

    Which is a disaster ! So how to avoid this ?

    Here thanks the top voted solution from @leetchunhui

    class Solution {
        void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
            int i=m-1, j=n-1, k=m+n-1;
            while(i>=0 && j>=0){
            while(j>=0) nums1[k--]=nums2[j--];

    This is a clear enough solution ! But can we optimize it more ?

    I will update once I think a better solution !

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.