数组中出现次数超过一半的数字
2017-08-14 11:19
190 查看
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0
代码如下:
<?php
function MoreThanHalfNum_Solution($numbers)
{
// write code here
$arr_count = count($numbers);
$count = array_count_values($numbers);
$half_arr_count = $arr_count/2;
foreach($count as $k=>$v) {
if($v > $half_arr_count) {
$arr_list[] = $k;
}
}
if(!empty($arr_list)) {
return $arr_list[0];
}else {
return 0;
}
}
代码如下:
<?php
function MoreThanHalfNum_Solution($numbers)
{
// write code here
$arr_count = count($numbers);
$count = array_count_values($numbers);
$half_arr_count = $arr_count/2;
foreach($count as $k=>$v) {
if($v > $half_arr_count) {
$arr_list[] = $k;
}
}
if(!empty($arr_list)) {
return $arr_list[0];
}else {
return 0;
}
}
相关文章推荐
- 剑指Offer(39)数组中出现次数超过一半的数字
- 微软等数据结构+算法面试100题(23)--数组中超过出现次数超过一半的数字
- 剑指offer-数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中有一个数字出现的次数超过了数组长度的一半,找出这个数字。
- 数组中出现次数超过一半的数字
- 剑指offer第二十八题【数组中出现次数超过一半的数字】c++实现
- 数组中超过出现次数超过一半的数字
- 剑指offer 29. 数组中出现次数超过一半的数字
- 面试题29:数组中出现次数超过一半的数字
- Q29:数组中出现次数超过一半的数字
- 牛客网刷题之数组中出现次数超过一半的数字
- 【剑指offer】Q29:数组中出现次数超过一半的数字
- 剑指offer-数组中出现次数超过一半的数字-php
- 数组中出现次数超过一半的数字
- 面试题29:数组中出现次数超过一半的数字
- 剑指offer 数组中出现次数超过一半的数字
- 找到数组中出现次数超过一半的数字
- 数组中有一个数字出现的次数超过数组长度的一半
- 数据结构与算法分析笔记与总结(java实现)--数组4:数组中出现次数超过一半的数字