leetcode-169 多数元素 Python
2020-03-15 12:13
681 查看
方法一:
class Solution: def majorityElement(self, nums: List[int]) -> int: dic = {} for i in nums: dic[i] = dic.get(i, 0) + 1 if dic[i] >= len(nums)/2: return i
方法二:
class Solution: def majorityElement(self, nums: List[int]) -> int: if not nums: return None dic = {} for i in nums: if i not in dic: dic[i] = 1 else: dic[i] += 1 max = 0 for key.val in dic.items(): if val > max: max = val pos = key if max > int(len(nums)/2): return pos
方法三:
class Solution: def majorityElement(self, nums: List[int]) -> int: if not nums: return None dic = {} for i in nums: if i not in dic: dic[i] = 1 else: dic[i] += 1 max = 0 for key, val in dic.items(): if val > max: max = val pos = key if max > int(len(nums)/2): return pos
方法四:投票算法
class Solution: def majorityElement(self, nums: List[int]) -> int: m = cm = 0 for num in nums: if m == num: cm += 1 elif cm == 0: m = num cm = 1 else: cm -= 1 return m
方法五:排序
class Solution: def majorityElement(self, nums: List[int]) -> int: nums.sort() return nums[len(nums)//2]
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- LeetCode Problem 169: Majority Element查找多数元素
- LeetCode 题解 169. Majority Element(查找多数元素)
- [LeetCode] 169. Majority Element 多数元素
- [LeetCode]169. Majority Element(多数元素)
- [LeetCode Problem]169:Majority Element查找多数元素
- LeetCode-169:Majority Element (数组中的多数元素)
- leetcode-腾讯精选练习(50 题)python #169 求众数
- LeetCode--Majority Element(出现次数最多的元素)Python
- LeetCode--Move Zeroes(移动0元素)Python
- leetcode_169(主元素查找)
- LeetCode217.python实现: 存在重复元素问题☆
- Python LeetCode(27.移除元素)
- LeetCode 题 - 66. 列表元素加一 python实现
- LeetCode215. python实现:数组中的第K个最大元素问题☆☆
- 169. Majority Element 查找多数元素
- LeetCode刷题笔记82: 删除排序链表中的重复元素 II(Python实现)
- leetcode 169. Majority Element 多数投票算法(Boyer-Moore Majority Vote algorithm)
- leetcode--删除排序链表中的重复元素--python
- leetcode 计算二叉树中出现最多的元素,Python实现
- LeetCode 82. 删除排序链表中的重复元素 II Python