本文介绍了如何找到在一个数组中重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有n个元素(数字或单词)的阵列,我想找到所有发生的比数组中多次的元素。什么是在性能方面这样做的最有效的方法?
Let's say I have an array of n elements(numbers or words), I want to find all the elements which occur more than once in the array. What is the most efficient approach of doing this in terms of performance?
PS:我可以在阵列第一排序,但只有当没有太大影响的总性能。此外,虽然这主要是PHP的,我想知道一个算法或逻辑可以在其他平台上实现了。
PS: I can sort the array first, but only if that doesn't affect the total performance much. Also, though this is mainly php, i would like to know a algorithm or logic that can be implemented on other platforms too.
推荐答案您可以使用的 array_count_values 和 array_filter
$array = array(1, "hello", 1, "world", "hello"); $new=array_filter(array_count_values($array),'custom_filter'); print_r($new); function custom_filter($val) { return $val > 1; }输出
Array ( [1] => 2 [hello] => 2 )更多推荐
如何找到在一个数组中重复的元素?
发布评论