Leetcode练习(Python):数组类:第169题:给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出

2020-04-24 15:34:06 蜻蜓队长

题目:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。  你可以假设数组是非空的,并且给定的数组总是存在多数元素。  
思路:
使用哈希非常方便
程序:
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums.sort()
        length = len(nums)
        if length <= 0:
            return 0
        if length == 1:
            return nums[0]
        my_hashMap = {}
        for index in nums:
            if index in my_hashMap:
                my_hashMap[index] += 1
            else:
                my_hashMap[index] = 1
            if my_hashMap[index] > len(nums) // 2:
                return index

以上内容来自于网络,如有侵权联系即删除
相关文章

上一篇: 20.4.24 二进制链表转整数 简单 1290

下一篇: RESTful架构

客服紫薇:15852074331
在线咨询
客户经理