My 0ms Java solution.


  • 0
    S
    // Assume nums1 uses first m numbers, and backward merger, then shift positions
    
    public class Solution {
        public void merge(int[] nums1, int m, int[] nums2, int n) {
            int p = nums1.length; // to the last item
            int numOfPos = nums1.length - n - m;
            while (n > 0 && m > 0){
                int a = nums1[m -1];
                int b = nums2[n -1];
                nums1[--p] = a >= b ? nums1[--m] : nums2[--n];
            }
            while (n > 0){
                nums1[--p] = nums2[--n];
            }
            while (m > 0){
                nums1[--p] = nums1[--m];
            }
            if (numOfPos > 0) shiftLeft(numOfPos, nums1);
        }
        public void shiftLeft (int numOfPos, int[] arr){
            for (int i = 0; i < arr.length - numOfPos; i++){
                arr[i] = arr[i+numOfPos];
            }
        }
    }

Log in to reply
 

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