zoukankan      html  css  js  c++  java
  • [leedcode 229] Majority Element II

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
            /*首先,可以通过分析得到结论:满足条件的数字个数cnt最多为2。 
      证明: ifcnt>2⇒cnt× (⌊n/3⌋+1 )>n 超出原数组的大小。 
      然后,借鉴在数组中求出现次数超过一半的数这道题的思路: 
       
      1). 第一遍扫描,设两个计数器和变量记录数组nums[]中出现频率最高的数。 
      2). 第二遍扫描,计算着两个数出现的次数。 
      3). 判断这两个数是否符合要求,符合则存入结果集。
      需要注意的是:
      第一个for循环的判断顺序,首先要判断是否等于m或n
      */
            List<Integer> res=new ArrayList<Integer>();
            if(nums==null||nums.length<=0) return res;
            int m=0;
            int n=0;
            int countm=0;
            int countn=0;
            
            for(int i=0;i<nums.length;i++){
                
                
               /*if(m==nums[i]) countm++;
               else if(n==nums[i]) countn++;
               else if(countm==0){
                   countm=1;
                   m=nums[i];
               }else if(countn==0){
                   countn=1;n=nums[i];
               }else {
                    countm--;
                    countn--;
                }*/
                
                
                if(m==nums[i]||countm==0){
                    countm++; m=nums[i];
                }else if(n==nums[i]||countn==0){
                    countn++; n=nums[i];
                }else{
                    countm--;countn--;
                }
            }
            countm=0;
            countn=0;
           for(int i=0;i<nums.length;i++){
               if(nums[i]==m) countm++;
               else if(nums[i]==n) countn++;
           }
           if(countm>nums.length/3) res.add(m);
           if(countn>nums.length/3) res.add(n);
            return res;
        }
    }
  • 相关阅读:
    shell 表达式
    manjaro 换源到中国并按照速度排序
    ORA-01950:对表空间 'USERS' 无权限
    normal 普通身份 sysdba 系统管理员身份 sysoper 系统操作员身份 dba和sysdba
    学生选课数据库SQL语句练习题
    多线程编程
    补充知识点
    输入输出
    集合作业
    银行(1)0925
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4713306.html
Copyright © 2011-2022 走看看