题目链接:https://leetcode-cn.com/problems/majority-element/

题目大意:

  略。

分析:

   略.

代码如下:

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int ans = nums[0];
 5         int cnt = 1;
 6         
 7         for(int i = 1; i < nums.size(); ++i) {
 8             if(ans == nums[i]) ++cnt;
 9             else { // 两个两个消,最后剩下来的就是众数
10                 if(--cnt < 0) {
11                     ans = nums[i];
12                     cnt = 1;
13                 }
14             }
15         }
16         
17         return ans;
18     }
19 };
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
  • 2021-04-15
  • 2021-10-03
猜你喜欢
  • 2021-08-06
  • 2021-12-04
  • 2021-05-18
  • 2022-01-16
  • 2021-09-25
  • 2021-08-28
  • 2021-10-16
相关资源
相似解决方案