169. Majority Element:Python
程序员文章站
2022-07-25 15:24:11
169. Majority Element
Given an array of size n, find the majority element. The majority e...
169. Majority Element
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.
思路:
将列表中的数值进行一个出现次数的统计,然后判断出现最多次数的元素次数是否满足条件,是则输出。(这里用了2个for循环,效率不是很高,提交时速度只打败了50%不到的其他提交者,还有很大改进的余地)
代码:
class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ dic = {} for i in range(len(nums)): if nums[i] in dic: dic[nums[i]] += 1 else: dic[nums[i]] = 1 HighValue = 0 HighKey = None for each in dic: if dic[each] > HighValue: HighValue = dic[each] HighKey = each if HighValue>len(nums)//2: return HighKey
上一篇: HTML5新增核心工具——canvas
推荐阅读
-
vue element之axios下载文件(后端Python)
-
leetcode-169-Majority Element
-
python使用xpath中遇到:
到底是什么? -
169. Majority Element:Python
-
python自动化测试之web运行代码报错:selenium.common.exceptions.NoSuchElementException: Message: no such element
-
python报错ValueError: The truth value of an array with more than one element is ambiguous. Use a.any()
-
Python报错:The truth value of an array with more than one element is ambiguous
-
Python ValueError: The truth value of an array with more than one element is ambiguous.
-
成功解决Python的ValueError: The truth value of an array with more than one element is ambiguous
-
vue element之axios下载文件(后端Python)