Header Ad

Leetcode Merge Sorted Array problem solution

In this Leetcode Merge Sorted Array problem solution, You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The function should not return the final sorted array, but instead, be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

Leetcode Merge Sorted Array problem solution


Problem solution in Python.

def merge(self, nums1, m, nums2, n):
        i=0
        for x in range(len(nums1)):
            if i>=n:
                break
            if nums1[x]==0:
                nums1[x]=nums2[i]
                i+=1           
        nums1.sort()



Problem solution in Java.

public void merge(int A[], int m, int B[], int n) {
        int insertIndex = m+n-1;
        int indexA = m-1,indexB = n-1;
        
        while(indexB>=0){
            if(indexA<0){
                A[insertIndex--] = B[indexB--];
            }else{
                if(B[indexB]>=A[indexA]){
                    A[insertIndex--] = B[indexB--];
                }else{
                    A[insertIndex--] = A[indexA--];
                }
            }
        }
    }


Problem solution in C++.

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i=0, j=0;
        vector<int> nums;
        while(1)
        {
            if(i==m)
            {
                while(j<n)
                {
                    nums.push_back(nums2[j]);
                    j++;
                }
                break;
            }
            
            else if(j==n)
            {
                while(i<m)
                {
                    nums.push_back(nums1[i]);
                    i++;
                }
                break;
            }
            
            else
            {
                if(nums1[i] < nums2[j])
                {
                    nums.push_back(nums1[i]);
                    i++;
                }
                else
                {
                    nums.push_back(nums2[j]);
                    j++;
                }
            }
        }
        
        for(i=0; i<m+n; i++)
            nums1[i] = nums[i];
    }
};


Problem solution in C.

int compare (int *a, int *b){
    
    return *a > *b;
}

void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){

    int i;
    
    for(i = 0; i < n; i++){
        
        nums1[m + i] = nums2[i];
    }
    
    qsort(nums1, nums1Size, sizeof(int), compare);
    
}


Post a Comment

0 Comments