LintCode-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)

标签

LintCode 版权所有 贪心 枚举法 Zenefits

code

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: The majority number
     */
    int majorityNumber(vector<int> nums) {
        // write your code here
        int size = nums.size();
        int result, count;

        if(size > 0) {
            result = nums[0];
            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;
        }
    }
};
posted @ 2017-05-04 16:38  LiBaoquan  阅读(404)  评论(0编辑  收藏  举报