LeetCode 88: Merge Sorted Array solution

Here is my solution for Merge Sorted Array problem in PHP. This is not the most efficient solution.

class Solution {

    /**
     * @param Integer[] $nums1
     * @param Integer $m
     * @param Integer[] $nums2
     * @param Integer $n
     * @return NULL
     */
    function merge(&$nums1, $m, $nums2, $n) {
        if ($n == 0) {
            return;
        }
        
        if ($m == 0) {
            for ($i=0; $i<$n; $i++) {
                $nums1[$i] = $nums2[$i];
            }
        }
        
        $i = 0;
        $j = 0;
        
        while ($i<$m && $j<$n) {
            if ($nums1[$i]<=$nums2[$j]) {
                $i++;
            } else {
                $this->array_insert($nums1, $i++, $nums2[$j]);
                $m++;
                $j++;
            }   
        }
        
        while ($j < $n) {
            $nums1[$i++] = $nums2[$j++];
        }
        
    }
    
    function array_insert(&$arr, $i, $num) {
        $endArr = array_slice($arr, $i);
        //print_r($endArr);
        $arr[$i] = $num;
        
        for ($x=$i+1; $x<count($arr); $x++) {
            //print_r($arr);
            $arr[$x] = array_shift($endArr);
        }
    }
}

Leave a Reply