剑指offer——41数组中出现次数超过一半的数字

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
 
题解:
  没什么讲的
  
 1 class Solution {
 2 public:
 3     int MoreThanHalfNum_Solution(vector<int> numbers) {
 4         unordered_map<int, int>map;
 5         for (auto a : numbers)
 6         {
 7             map[a]++;
 8             if (map[a] > numbers.size() / 2)
 9                 return a;
10         }
11         return 0;
12     }
13 };

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11688947.html
今日推荐