zoukankan      html  css  js  c++  java
  • 【leetcode】Majority Element (easy)(*^__^*)

    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.

    思路:

    找主要元素,用major记录主要字母,n记录major相对于其他字母多出现的次数

    if         n == 0 , 设当前数字为主要数字

    else if   当前数字等于主要数字, n++

    else     当前数字不等于主要数字, n--

    因为主要数字出现多于一半,所以最后major表示的一定是主要数字。

    没测试就一次AC了 

    class Solution {
    public:
        int majorityElement(vector<int> &num) {
            int major;
            int n = 0;
    
            for(int i = 0; i < num.size(); i++)
            {
                if(n == 0)
                {
                    major = num[i]; n++;
                }
                else if(major == num[i])
                {
                    n++;
                }
                else
                {
                    n--;
                }
            }
            return major;
        }
    };
  • 相关阅读:
    ryzen nvidia hackintosh
    mysql count 主键之坑
    git命令
    MYSQL 注释
    yaf twig配置
    1.YAF 的安装
    yaf nginx 设置
    ubuntu 16 阿里云 vsftpd
    win10下 homestead 安装
    活动调度
  • 原文地址:https://www.cnblogs.com/dplearning/p/4214245.html
Copyright © 2011-2022 走看看