[LeetCode-169]⌊n / 2⌋回を超える配列内の出現回数を検索します

// メソッド1 
    パブリック 静的 int MajorElement_1(int [] num){ 

        int major = num [0]、count = 1 ; 
        
        forint i = 1; i <num.length; i ++ ){
             if(count == 0 ){ 
                count ++ ; 
                メジャー = num [i]; 
            } else  if(major == num [i]){ 
                count ++ ; 
            } else count-- ; 
            
        } 
        メジャーリターン; 
    }
    
    // 方法2 
    公共 静的 INT majorityElement_2(INT [] NUMS){ 
        は、Arrays.sort(NUMS)。
        nums [nums.length / 2 ];を返します。
    } 
    
    // メソッド3 
    public  static  int majorElementElement_3 int [] nums){ 
         Map <Integer、Integer> myMap = new HashMap <Integer、Integer> ();
            // Hashtable <Integer、Integer> myMap = new Hashtable <Integer、Integer>(); 
            int ret = 0 ;
            forint num:nums){
                if(!myMap.containsKey(num))
                    myMap.put(num、 1 );
                それ以外の場合は
                    myMap.put(num、myMap.get(num) +1 );
                if(myMap.get(num)> nums.length / 2 ){ 
                    ret = num;
                    休憩; 
                } 
            } 
            return ret; 
    }

 

おすすめ

転載: www.cnblogs.com/nachdenken/p/12737711.html