zoukankan      html  css  js  c++  java
  • 数组中出现次数超过一半的数字

    ##题目描述 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

    思路

    使用pre记录上一次访问的值,count表明当前值出现的次数,下一个值和当前值相同count++,不同count--,减到0时更新pre,如果存在超过数组长度一半的值,那么最后pre一定会是该值(也可能不存在)。
    时间复杂度O(n),空间复杂度O(1)。

    代码

    public class Solution {
        public int MoreThanHalfNum_Solution(int [] array) {
            if(array == null || array.length == 0)    return 0;
            int count = 1;
            int pre = array[0];
            for(int i = 1; i < array.length; i++) {
                if(array[i] == pre) {
                    count++;
                } else {
                    count--;
                    if(count == 0) {
                        pre = array[i];
                        count = 1;
                    }
                }
            }
            count = 0;
            for(int i = 0; i < array.length; i++) {
                if(array[i] == pre) {
                    count++;
                }
            }
            return count > array.length / 2 ? pre : 0;
        }
    }
    
  • 相关阅读:
    Codeforces Round #564 (Div. 1)
    Codeforces Round #569 (Div. 1)
    SDOI2019R2游记
    BZOJ 3555: [Ctsc2014]企鹅QQ
    SDOI2019R1游记
    计数的一些东西
    多项式的各种操作
    BZOJ 5424: 烧桥计划
    Codeforces Round #545 (Div. 1)
    概率期望学习笔记
  • 原文地址:https://www.cnblogs.com/ustca/p/12348962.html
Copyright © 2011-2022 走看看