"Numbers that appear more than half of the times in the array" in "The Sword Offer"

Topic description


There is a number in the array that occurs more than half the length of the array, please find the number. For example enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which is more than half the length of the array, 2 is output. Output 0 if not present.

Code


class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        int n = numbers.size();
        if (n == 0) return 0;

        int num = numbers[0], count = 1;
        for (int i = 1; i < n; i++) {
            if (numbers[i] == num) count++;
            else count--;
            if (count == 0) {
                num = numbers[i];
                count = 1;
            }
        }
        // Verifying
        count = 0;
        for (int i = 0; i < n; i++) {
            if (numbers[i] == num) count++;
        }
        if (count * 2 > n) return num;
        return 0;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609354&siteId=291194637