面试题39. 数组中出现次数超过一半的数字

题目:

 

 

解答:

 

 

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) 
 4     {
 5         int x = 0;
 6         int votes = 0;
 7         for(int num : nums)
 8         {
 9             if(votes == 0) 
10             {
11                 x = num;
12             }
13             if (num == x)
14             {
15                 votes += 1;
16             }
17             else
18             {
19                 votes -= 1;
20             }
21             // votes += num == x ? 1 : -1;
22         }
23         return x;
24     }
25 };

 

posted @ 2020-05-09 16:23  梦醒潇湘  阅读(127)  评论(0)    收藏  举报