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条回答
放我归山
2楼-- · 2020-07-09 09:18
$arrs = array(12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98);

static $repeat  = '';

foreach($arrs as $arr) {

   if ((count(array_keys($arrs,$arr))) > 1) {

        $repeat = $arr;
        break;

   }

}

if ($repeat) echo 'The first repeated element out of the array of integers is '.$repeat;


//This solution is working for associate array too, for example:

// $arrs = array('a'=>12, 'b'=>46, 'c'=>244, 'd'=>0, 'e'=>12, 'f'=>83, 'g'=>48, 'h'=>98, 'i'=>233, 'j'=>83, 'k'=>26, 'l'=>91, 'm'=>119, 'n'=>148, 'o'=>98);
查看更多
女痞
3楼-- · 2020-07-09 09:23
function findDuplicate ($array) {
  while (($item = array_shift($array)) !== null) {
    if (in_array($item, $array)) return $item;
  }
}
查看更多
够拽才男人
4楼-- · 2020-07-09 09:25
$arrs = array(12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98);

// or a associate array like as $arrs = array('a'=>12, 'b'=>46, 'c'=>244, 'd'=>0, 'e'=>12, 'f'=>83, 'g'=>48, 'h'=>98, 'i'=>233, 'j'=>83, 'k'=>26, 'l'=>91, 'm'=>119, 'n'=>148, 'o'=>98);

$data = "12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98";

static $repeat  = '';

foreach($arrs as $arr){

   if (substr_count($data,$arr)>1) {

     $repeat = $arr;
     break; 
  }

}

if ($repeat) echo 'The first repeated element out of the array of integers is '.$repeat;
查看更多
走好不送
5楼-- · 2020-07-09 09:25
function getFirstRepetition($array) {
    $prev = array();
    foreach($array as $value) {

        if (in_array($value, $prev)) {
            return $value;
        }

        $prev[] = $value;
    }
    return FALSE;
}

CodePad.

查看更多
爷、活的狠高调
6楼-- · 2020-07-09 09:25
$array = array(12, 46, 46, 0, 18, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98);
$count_array = array_count_values($array);
foreach($count_array as $key=>$value)
{
    if($value>=2)
    {
       echo $key;
       break;
    }

}
查看更多
欢心
7楼-- · 2020-07-09 09:26

You could use array_unique to remove all the duplicate values, then iterate over the original and resulting arrays and return the first value that doesn't appear in the resulting array. Something like this:

$arr = array(12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98);

function first_dupe($arr) {
    $res = array_unique($arr);

    foreach ($arr as $key => $val) {
        if ($res[$key] !== $val)
            return $val;
    }
}

echo first_dupe($arr);

Working demo: http://codepad.org/atFMrhLW.

查看更多
登录 后发表回答