JAVA Solutions | Easy to Understand | Takes advantage of the sorted array


  • 0
    M
    public void merge(int[] nums1, int m, int[] nums2, int n) {
            
            // Length of nums1 > size of nums2 so as to hold elements of nums2
            int i = nums1.length - 1;
            int j = n - 1;
            int k = m - 1;
            
            while (k >= 0 && j >= 0) {
                if (nums1[k] > nums2[j]) {
                    nums1[i] = nums1[k];
                    k--;
                } else {
                    nums1[i] = nums2[j];
                    j--;
                }
                i--;
            }
            
            while (j >= 0) {
                nums1[i] = nums2[j];
                j--;
                i--;
            }
        }
    

Log in to reply
 

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