题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { int len = numbers.size(); for(int i = 1; i < len; ++ i){ for(int j = i; j > 0; --j){ if (numbers[j] < numbers[j - 1]){ int temp; temp = numbers[j]; numbers[j] = numbers[j-1]; numbers[j-1] = temp; } } } int val = numbers[len/2]; int counts_ = 0; for(int k = 0; k < len; ++k) if(numbers[k] == val) counts_ ++; if(counts_ > len/2) return val; else return 0; } };
注: 先排序,然后判断中间元素的个数是否超过数组长度的一半;
最后
以上就是淡定飞鸟最近收集整理的关于数组中有一个数字出现的次数超过数组长度的一半......的全部内容,更多相关数组中有一个数字出现内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复