【編程練習】出現最多的數

數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度爲9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。

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