More than half of the number of times an array of numbers that appear (17)

topic

There are a number of [array number that appears more than half the length of the array, find this number. For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output. ]


1, analysis:
setting a starting value for the element, while the latter elements thereto, the count value plus 1, minus 1 otherwise. Until the last time the count is set to an array of more than half of the number of times it occurs when the 1.
2, Code:

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.size()==0)
            return 0;
        if(numbers.size()==1)
            return numbers[0];
        int count=1,res=numbers[0];
        for(int i=0;i<numbers.size();++i)
        {
            if(numbers[i]==res)
                count++; //遇到相同的元素就自加1
            else 
                count--; //遇到不同的元素就减1
            //当遇到不同元素减1后,相当于两个元素抵消了,此时需要重新设置
            if(count==0) 
            {
                res=numbers[i];
                count=1;
            }
        }
        // 验证当count最后一次被置为1时,所得的数据就是最终的结果
        int tempCount=0;
        for(int i=0;i<numbers.size();++i)
        {
            if(res==numbers[i])
                ++tempCount;
        }
        if(tempCount>numbers.size()/2)
        {
            return res;
        }
        else
            return 0;
    
    }
};
Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104688533