LeetCode--Majority Element(出现次数最多的元素)Python
2017-12-08 14:31
881 查看
题目:
给定一个数组,长度为n,求出出现次数>=下取整(n/2)的元素。
解题思路:
考虑使用哈希表存储各个元素出现的次数,只用遍历一遍数组即可,复杂度为O(n)
代码(Python):
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
N = len(nums)
Dict = {}
for i in nums:
if i not in Dict:
Dict[i] = 1
else:
Dict[i] = Dict[i]+1
if Dict[i]>=(N+1)/2:
return i
给定一个数组,长度为n,求出出现次数>=下取整(n/2)的元素。
解题思路:
考虑使用哈希表存储各个元素出现的次数,只用遍历一遍数组即可,复杂度为O(n)
代码(Python):
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
N = len(nums)
Dict = {}
for i in nums:
if i not in Dict:
Dict[i] = 1
else:
Dict[i] = Dict[i]+1
if Dict[i]>=(N+1)/2:
return i
相关文章推荐
- Leetcode:169. Majority Element(找到数组中出现次数最多的元素)
- leetcode Majority Element 寻找出现次数最多元素
- leetcode_Majority Element (找出现次数大于一半的元素)-easy
- [LeetCode169]Majority Element求一个数组中出现次数大于n/2的数
- Python实用黑科技——找出序列里面出现次数最多的元素
- leetcode 计算二叉树中出现最多的元素,Python实现
- ※ Leetcode - Array - 169. Majority Element(快速找出数组中出现过一半以上次数的数,3种写法)
- Python第三方库——Numpy_怎么得到向量中出现次数最多的元素值?
- python 找出序列中出现次数最多的元素方法。
- leetcode229-Majority Element II(数组中出现最多的数II)
- 输出列表中出现次数最多的元素 分类: python 2013-01-15 15:25 990人阅读 评论(0) 收藏
- LeetCode-501. Find Mode in Binary Search Tree (JAVA)出现次数最多的元素
- python找出序列中出现次数最多的元素之Counter对象
- Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算法示例
- leetcode169---Majority Element(数组中出现次数超过一半的数)
- 找出数组中出现次数最多的前k个元素[leetcode题]
- python 找出序列中出现次数最多的元素方法
- 输出数组中出现次数最多的元素
- JavaScript求一个数组中重复出现次数最多的元素及其下标位置示例
- LeetCode 题解 169. Majority Element(查找多数元素)