返回数组的第一个重复元素的最佳方法 [英] Best way to return the first repeated element of array

查看:107
本文介绍了返回数组的第一个重复元素的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个面试问题:

从整数数组中返回第一个重复元素的最佳方法是什么?

示例:

给出一个数组[12, 46, 244, 0, 12, 83, 48, 98, 233, 83, 26, 91, 119, 148, 98].

在这种情况下,返回值为12.

The return value in this case is 12.

这怎么办?

推荐答案

我认为,如果您看一下性能,foreach循环就是

i think that if you look of performance, foreach loop is the faster

# temp array
$array_help = array();

# run over the array
foreach ($array as $val) {

    if (isset($array_help[$val]))
     # found if is set already !
        return $val;

    else
       # its the first time this value appear
       $array_help[$val] = 1;
}

这篇关于返回数组的第一个重复元素的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆