Best way to return the first repeated element of a

2020-07-09 09:14发布

This is an interview question:

What is the best way to return the first repeated element out of the array of integers?

Example:

Given an array [12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98].

The return value in this case is 12.

How can this be done?

标签: php arrays
13条回答
Anthone
2楼-- · 2020-07-09 09:39
$arr = array(12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98);
$arrHelp = array();
foreach($arr as $int) {
    if (in_array($int, $arrHelp)) {
        echo $int;
        break;
    }
    else {
        array_push($arrHelp, $int);
    }
}
查看更多
登录 后发表回答