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

题目描述

 

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

 

解题思路

 

考虑记录两个值:一个是数组中的数字,另一个是他出现的次数。每遍历到一个数字,如果与保存值相同,则次数加1,否则减1;若次数减到0,则把记录值换成下一个数字。最后得到次数大于0的数字后,再从头遍历记录它出现的次数,同样进行上述步骤,若最后次数仍大于0,则为所需值。

 

代码

 

 1 class Solution {
 2 public:
 3     int MoreThanHalfNum_Solution(vector<int> numbers) {
 4         if(numbers.size() == 0)
 5             return 0;
 6         int mh = numbers[0];
 7         int count = 1;
 8         for(int i = 1; i < numbers.size(); i++){
 9             if(numbers[i] == mh){
10                 count++;
11             }
12             else{
13                 count--;
14                 if(count == 0 && i+1 != numbers.size()){
15                     mh = numbers[i + 1];
16                 }
17             }
18         }
19         if(count > 0){
20             count = 0;
21             for(int i = 0; i < numbers.size(); i++){
22                 if(mh == numbers[i])
23                     count++;
24                 else 
25                     count--;
26             }
27         }
28         if(count > 0)
29             return mh;
30         else
31             return 0;
32     }
33 };

 

posted @ 2018-03-25 10:36  FlyingWarrior  阅读(146)  评论(0编辑  收藏  举报