46. 主元素

46. 主元素 

 

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。

 注意事项

You may assume that the array is non-empty and the majority number always exist in the array.

样例

给出数组[1,1,1,1,2,2,2],返回 1

挑战 

要求时间复杂度为O(n),空间复杂度为O(1)

class Solution {
public:
    /*
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    int majorityNumber(vector<int> &nums) {
        // write your code here
            int size = nums.size();
            int result = nums[0];
            int count = 1;
        
            for (int i = 1; i < size; i++) {
                if (count == 0) {
                    result = nums[i];
                    count = 1;
                }
                if (result == nums[i])
                    count++;
                else
                    count--;
            }
            return result;
    }
};

  

原文地址:https://www.cnblogs.com/kanekiken/p/8005647.html