如何找到在一个数组中重复的元素?

编程入门 行业动态 更新时间:2024-10-21 13:25:05
本文介绍了如何找到在一个数组中重复的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我们说我有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 )

更多推荐

如何找到在一个数组中重复的元素?

本文发布于:2023-11-30 20:54:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651443.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在一   组中   个数   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!