zoukankan      html  css  js  c++  java
  • 169. Majority Element

    问题描述:

    Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

    You may assume that the array is non-empty and the majority element always exist in the array.

    Example 1:

    Input: [3,2,3]
    Output: 3

    Example 2:

    Input: [2,2,1,1,1,2,2]
    Output: 2
    
     
     

    解题思路:

    我们可以用map来存储值与数量的关系,但是那样的空间复杂度为O(n)

    这里学习一种O(1)的空间复杂度的解法:摩尔投票法(Moore Voting),能使用的前提是:一定有众数存在!

    我们首先设定第一个数字为众数候选者,设定计数器cnt为1

    然后这个时候遍历下一个数字,若下一个数字与候选者相等:cnt自增1;若不想等:自减一

    在每次遍历前我们要先检查当前计数器的值:

      若计数器为0,则设置当前数字位候选数字。

    代码:

    class Solution {
    public:
        int majorityElement(vector<int>& nums) {
            int candidate = nums[0];
            int cnt = 1;
            for(int i = 1; i < nums.size(); i++){
                if(cnt == 0){
                    candidate = nums[i];
                }
                if(nums[i] == candidate)
                    cnt++;
                else
                    cnt--;
            }
            return candidate;
        }
    };
  • 相关阅读:
    再叙存储设备
    分布式文件系统---测试
    分布式文件系统
    Solr 分布式(复制)配置--成功验证
    搜索服务之离线处理思路
    我为公司做的总体架构,欢迎提建议
    python的面向对象
    python异常处理
    迭代器和生成器
    python函数
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9227158.html
Copyright © 2011-2022 走看看