统计数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]输出: 2
因为没写过这种场景,自己实现的一版,仅供一种思路参考:
public static void main(String[] args) {
int[] array = {1, 2, 3,3, 3, 3, 3, 3, 2, 2, 2, 5, 4, 2};
int arrayLength = array.length;
Map<Integer,Integer> map = new HashMap<>();
for (int temp : array) {
Integer value = map.get(temp);
if (value == null) {
map.put(temp, 1);
continue;
}
map.put(temp, value + 1);
}
// 判断条件,数组长度除以2
float condition = arrayLength >> 1;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > condition) {
System.out.println(entry.getKey());
}
}
}
最后
以上就是动听大碗最近收集整理的关于【快手面试题】统计数组中出现次数超过一半的数字的全部内容,更多相关【快手面试题】统计数组中出现次数超过一半内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复