给定一个数组,我们必须找到第二个最常见的元素。
例子
1 2 3 4 5 | Input : array(3, 3, 4, 5, 5, 5, 9, 8, 8, 8, 8, 8); Output : Second most frequent element is: 5 Input : array("www", "sky8g", "com"); Output : Second most frequent element is: sky8g |
上述问题可以用循环方法在其他语言中解决,但在PHP中我们内置了函数来执行这个任务。其功能描述如下:
- array_count_values():该函数用于计算所有元素的频率,并返回相关联的数组,该数组包含作为键值的值和作为值的频率。
- arsort():该函数用于对元素进行反向排序,并维护相关的索引。
- array_keys():该函数返回一个包含所有键或子集的数组。
方法:首先,我们使用array_count_values创建一个包含所有元素频率的新数组,值作为键值,count作为值。
使用arsort对新数组进行反向排序,然后使用array_keys获取已排序数组的所有键。第二个键将是原始数组中第二个最常见的元素。
下面是上述方法的说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $arr = array(2, 2, 3, 4, 4, 4, 8, 8, 6, 6, 9, 9, 9, 9); // new array containing frequency of values of $arr $arr_freq = array_count_values($arr); // arranging the new $arr_freq in decreasing order // of occurrences arsort($arr_freq); // $new_arr containing the keys of sorted array $new_arr = array_keys($arr_freq); // Second most frequent element echo "Second most frequent element is:"." ".$new_arr[1]; ?> |
输出
1 | Second most frequent element is: 4 |
程序2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php $arr = array("www", "sky8g", "com"); // new array containing frequency of values of $arr $arr_freq = array_count_values($arr); // arranging the new $arr_freq in decreasing // order of occurrences arsort($arr_freq); // $new_arr containing the keys of sorted array $new_arr = array_keys($arr_freq); // Second most frequent element echo "Second most frequent string is:"." ".$new_arr[1]; ?> |
输出
1 | Second most frequent string is: sky8g |