内容简介:Given an array of sizeYou may assume that the array is non-empty and the majority element always exist in the array.给定一个大小为
- 英文:
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.
- 中文:
给定一个大小为 n
的数组,找到其中的众数。众数是指在数组中出现次数 大于
⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例
- 示例 1:
输入: [3,2,3] 输出: 3
- 示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
题解
- 题解 1
使用 set()
方法得到列表中不重复元素的元组,然后再遍历这个元组,使用列表的 count()
方法依次统计元组中元素在列表中出现的次数,然后查看出现是否大于 ⌊ n/2 ⌋
,如果是则输出该元素即可,因为在任何数组中,出现次数大于该数组长度一半的值只能有一个。
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = set(nums) # 不重复元素
for i in s:
con = nums.count(i) # 统计出现次数
if con > len(nums) // 2: # //为整数除法,返回不大于结果的一个最大的整数
return i # 返回结果
- 题解 2
使用 排序 法,排序后,出现次数大于一半的肯定在中间。
class Solution:
def majorityElement(self, nums):
nums.sort()
return nums[len(nums)//2]
- 题解 3
使用摩尔投票法。摩尔投票法的基本思想很简单,在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除。这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组长度的一半。如果只存在一种元素,那么这个元素则可能为目标元素。
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
res = 0
for i in nums: # 遍历数组
if count == 0 or i == res:
res = i
count += 1
else:
count -= 1
return res
以上所述就是小编给大家介绍的《LeetCode 169. Majority Element》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- LeetCode 169. Majority Element
- LeetCode - 169 - 求众数(majority-element)
- LeetCode 第169题 Majority Element【分而治之】(Java)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
网络机器人Java编程指南
美 Heaton J. / 电子工业出版社 / 2002-7 / 44.00元
这是一本研究如何实现具有Web访问能力的网络机器人的书。该书从Internet编程的基本原理出发,深入浅出、循序渐进地阐述了网络机器人程序Spider、Bot、Aggregator的实现技术,并分析了每种程序的优点及适用场合。本书提供了大量的有效源代码,并对这些代码进行了详细的分析。通过本书的介绍,你可以很方便地利用这些技术,设计并实现网络蜘蛛或网络信息搜索器等机器人程序。 适合于具有一起来看看 《网络机器人Java编程指南》 这本书的介绍吧!