您的位置:首页 > 其它

Leetcode: Majority Element

2015-08-27 02:58 274 查看

Question

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

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

Credits:

Special thanks to @ts for adding this problem and creating all test cases.

Show Tags

Show Similar Problems

Solution

Analysis

refer to here

Moore voting algorithm.

We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:

1. If the counter is 0, we set the current candidate to x and the counter to 1.

2. If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.

After one pass, the current candidate is the majority element. Runtime complexity = O(n).

Code

[code]class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        most, count = nums[0], 1
        for ind in range(1,len(nums)):
            if nums[ind]==most:
                count += 1
            else:
                if count==0:
                    most = nums[ind]
                else:
                    count -= 1

        return most
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: