题目

题意:找出数组里重复最多的元素,重复最多是指数量大于n/2的,

题解:题目说一定存在答案,不用额外的内存空间,怎么做呢?其实很简单,重复最多的元素的数量大于剩下所有元素数量之和,维护一个数字count,代表数量,维护一个变量a代表重复最多的元素。遇到相同的a,count++,遇到不同的count--,那么到最后count一定是大于0的,如果count等于0的时候,a的值就要更新。最后a的值一定是答案。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        
        int ans;
        int count=0;
        for(int i=0;i<nums.size();i++)
        {
            if(count==0)
            {
                ans=nums[i];
                count++;
            }
            else
            {
                if(nums[i]!=ans)
                    count--;
                else
                    count++;
            }
        }
        
        return ans;
        
    }
};

相关文章:

  • 2022-01-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2021-12-15
猜你喜欢
  • 2021-07-07
  • 2021-09-12
  • 2021-05-17
  • 2021-10-27
  • 2021-07-16
  • 2021-11-05
  • 2021-08-12
相关资源
相似解决方案