simple to understand C solution


  • 0
    S
    void merge(int* nums1, int m, int* nums2, int n) {
        int* temp = (int*)malloc(sizeof(int)*(m+n));
        int flag1=0;
        int flag2=0;
        int flagt=0;
        int i=0;
        while((flag1<m) && (flag2<n)){
            if(nums1[flag1]<=nums2[flag2]){
                temp[flagt]=nums1[flag1];
                flag1++;
            }else{
                temp[flagt]=nums2[flag2];
                flag2++;
            }
            flagt++;
        }
        // the reset of the n is larger than all the elements in m
        if(flag1==m){
            while(flag2<n){
                temp[flagt]=nums2[flag2];
                flag2++;
                flagt++;
            }
        }else if(flag2==n){
            while(flag1<m){
                temp[flagt]=nums1[flag1];
                flag1++;
                flagt++;
            }
        }
        
        for(i=0;i<(m+n);i++){
            nums1[i]=temp[i];
        }
        
        free(temp);
        
    }
    

Log in to reply
 

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