Working Java Solution O(m+n) with out extra space


  • 0

    Copy from the last to first in nums1 array

    class Solution {
        public void merge(int[] nums1, int m, int[] nums2, int n) {
            int i = m + n - 1;
            while(m > 0 && n > 0 && i>= 0) {
                
                    if(nums1[m-1] > nums2[n-1]){
                        nums1[i--] = nums1[m-1];
                        nums1[m-1] = Integer.MIN_VALUE;
                        m--;
    
                    } else {
                        nums1[i--] =nums2[n-1];
                        n--;
    
                    } 
            }
            if(m == 0 && n != 0) {
                while(i >= 0 && n > 0) {
                    nums1[i--] = nums2[n-1];
                    n--;
                }
            }
        }
    }
    

Log in to reply
 

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