【LeetCode】169. 主要元素

問題描述

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.

給定一個大小爲n的數組,找到多數元素。大多數元素的元素⌊n / 2⌋多次出現。
你可以假設數組是非空的,並且大多數元素始終存在於數組中。

輸入: [3,2,3]
輸出: 3

輸入: [2,2,1,1,1,2,2]
輸出: 2

Python 實現

第一種方法:對數組進行排序,然後取中間位置的那個元素,即爲主要元素。

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        major = nums[len(nums)/2]
        return major

第二種方法:博伊爾-摩爾投票算法(Boyer-Moore  majority vote algorithm),是一種使用線性時間複雜度和常數空間複雜度來找到數組的主要元素。因此,我們可以採取一種投票的形式,當一個標記的元素重複出現的時候,我們給它投一票,加一分,出現別的元素則對應減一分。當分數爲0時,則用下一個元素來作爲新的標記元素。這樣到最後,出現次數最多的那個元素必然是最後仍然被標記的元素。

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

        ret = None
        score = 0
        for num in nums:
            if score == 0:
                ret = num
            # Scoring for the number existing.
            if ret == num:
                score += 1
            else:
                score -= 1
        return ret

鏈接:https://leetcode.com/problems/majority-element/

發佈了46 篇原創文章 · 獲贊 29 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章