找出一組數中個數超過一半的數

問題描述

問題:找出一組數中個數超過一半的數,時間複雜度O(n)
輸入:一組數(其中必有一個數的個數是超過一半的)例: 1 1 2 4 1 3 1 2 1
輸出:數字 例: 1

代碼

public static int findMostApperse(int[] a){
        int candidate=0;
        int count=0;
        int len=a.length;

        for(int i=0;i<len;i++){
            if(count==0){
                candidate=a[i];
                count=1;
            }else{
                if(candidate==a[i])
                    count++;
                else
                    count--;
            }
        }
        return candidate;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章