Merge Two Sorted Arrays
PHP
Medium
4 views
Problem Description
Given two sorted arrays, merge them using a function and print the merged list.
Input Format
Line1 n m. Line2 n ints. Line3 m ints.
Output Format
One line merged.
Sample Test Case
Input:
3 4
1 4 9
2 3 8 10
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0;
$n=intval($tokens[$i++] ?? 0);
$m=intval($tokens[$i++] ?? 0);
$a=[]; $b=[];
for($k=0;$k<$n;$k++) $a[] = intval($tokens[$i++] ?? 0);
for($k=0;$k<$m;$k++) $b[] = intval($tokens[$i++] ?? 0);
function merge2($a,$b){
$i=0; $j=0; $output=[];
while($i<count($a) && $j<count($b)){
if($a[$i]<=$b[$j]) $output[]=$a[$i++];
else $output[]=$b[$j++];
}
while($i<count($a)) $output[]=$a[$i++];
while($j<count($b)) $output[]=$b[$j++];
return $output;
}
$res=merge2($a,$b);
echo implode(' ',array_map('strval',$res));
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!