LeetCodeEasy-【面試題39. 數組中出現次數超過一半的數字】

數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。
你可以假設數組是非空的,並且給定的數組總是存在多數元素。

示例 1:
輸入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
輸出: 2

限制:
1 <= 數組長度 <= 50000

注意:本題與主站 169 題相同:https://leetcode-cn.com/problems/majority-element/

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路1:map

直接遍歷list,然後利用map統計每個數字出現的次數。
在這裏插入圖片描述

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        map = {}
        for num in nums:
            if num in map:
                map[num] += 1
            else:
                map[num] = 1
            if map[num] > len(nums) / 2:
                return num 
        return 0

思路2:排序

應爲超過數量一半的數,在list排序後,中位數一定是它。所以直接排序後取出來就行了。
在這裏插入圖片描述

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        return nums[len(nums)//2]

思路3:摩爾投票

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        x = nums[0]
        score = 0
        for num in nums:
            if score == 0:
                x = num
            if x == num:
                score -= 1
            else:
                score += 1
        return x
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章