Java AC solution in O(m+n) time


  • 0
    G
    class Solution {
        public void merge(int[] nums1, int m, int[] nums2, int n) {
            if(nums1.length == 0 && nums2.length == 0)
                return;
            
            int[] result = new int[m + n];
            int i = 0, j = 0, k = 0;
            
            while(i < m && j < n)   //compare and map elemnets from both the array
            {
                if(nums1[i] < nums2[j]) //insert elements to result array from nums1 if its less than nums2
                {
                    result[k] = nums1[i];
                    i++;
                    k++;
                }
                else    //insert elements to result array from nums2 if its less than nums1
                {
                    result[k] = nums2[j];
                    j++;
                    k++;
                }
            }
            
            while(i < m)
            {
                result[k] = nums1[i];   //insert remaining elements from nums1
                i++;
                k++;
            }
            
            while(j < n)
            {
                result[k] = nums2[j];   //insert remaining elements from nums2
                j++;
                k++;
            }
            
            for(int p = 0; p<m+n; p++)
                nums1[p] = result[p];   //put back from results to nums1
        }
    }
    

Log in to reply
 

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