Numbers that appear more than half the times in the sword index group

topic link

I have encountered this question many times, but every time I don't think about it seriously, I always want to map statistics and the like, which wastes space.

There is a good practice:

save two values ​​when traversing the array: one is a number in the array, and the other is the number of times. When traversing the next number, if it is the same as the previously saved number, the number is increased by 1, otherwise the number is decreased by 1; if the number is 0, the next number is saved and the number is set to 1. After the traversal is over, the saved number is the desired one. Then you can determine whether it meets the conditions.

 

Because more than half must make the number of times a positive number.

 

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.size() == 0) return 0;
        int time = 1;
        int result = numbers[0];
        for(int i = 1; i < numbers.size(); i++) {
            if(time == 0) {
                time = 1;
                result = numbers[i];
                continue;
            }
            if(result == numbers[i]) {
                time++;
            } else {
                time--;
            }
        }
        time = 0;
        for(int i = 0; i < numbers.size(); i++) {
            if(result == numbers[i]) time++;
        }
        return time > numbers.size()/2? result: 0;
    }
};

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326637062&siteId=291194637