Intersection (Unique Sorted)
PHP
Medium
9 views
Problem Description
Given two arrays, print unique common values in increasing order.
Input Format
Line1 n m. Line2 n ints. Line3 m ints.
Output Format
One line values.
Sample Test Case
Input:
5 6
1 2 2 3 4
2 2 4 6 1 1
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);
$sa=[]; foreach($a as $v) $sa[$v]=true;
$res=[];
foreach($b as $v) if(isset($sa[$v])) $res[$v]=true;
$vals=array_keys($res);
sort($vals);
echo implode(' ',array_map('strval',$vals));
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!