Readable, 0ms Java Solution


  • 0
    C

    The 'index' pointer is the actual position in the nums1 array to shift current element to. Start comparing from ends of both the occupied number lists.
    At the end if it is the smaller (nums2) array that ran out first, continue, since the elements in nums1 are where they should be anyway.
    However, copy the rest from nums2 if nums1 was the array that ran out first.

    public void merge(int[] nums1, int m, int[] nums2, int n) {
            int i = m - 1, j = n - 1;
            int index = i + j + 1;
            
            while(i >= 0 && j >= 0) {
                if(nums1[i] >= nums2[j]) {
                    nums1[index] = nums1[i];
                    i--;
                }
                else {
                    nums1[index] = nums2[j];
                    j--;
                }
                index--;
            }
            
            while(j >= 0 && index >= 0) {
                nums1[index] = nums2[j];
                j--;
                index--;
            }
            
        }
    

Log in to reply
 

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