Concise and easy to understand Java solution, 0ms


  • 0
    W

    Merge from the back to the front. The first while loop handles the case when both arrays still have elements to be compared. The second while loop handles the case when either array runs out of elements to be compared.

    public class Solution {
        public void merge(int[] nums1, int m, int[] nums2, int n) {
            int i = nums1.length-1;
            
            while (i >= 0 && m > 0 && n > 0) {
                nums1[i--] = nums1[m-1] >= nums2[n-1] ? nums1[--m] : nums2[--n];
            }
            
            while (i >= 0 && (m > 0 || n > 0)) {
                nums1[i--] = m > 0 ? nums1[--m] : nums2[--n];
            }
        }
    }
    

Log in to reply
 

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