题目描述:
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
方法一、
利用while循环,使得重复运行,直到列表同样的数的长度超过了n/2截至。
for i in range (len(nums)-1,-1,-1):
if nums[i] == record_numbers[0]:
nums.remove(nums[i])
从上面的代码可以看出来,range函数有三个参数,以此为start,end,step。其中,start不一定必须比end小,只要最后可以从start算到end即可!
还要注意的是,remove删除只能删除遇到的第一个符合条件的值,如果想要把所有的都删除必须在循环中实现。
code:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
numbers = len(nums)/2
record_numbers = []
while len(record_numbers) <= numbers:
if record_numbers:
for i in range (len(nums)-1,-1,-1):
if nums[i] == record_numbers[0]:
nums.remove(nums[i])
result = nums[0]
record_numbers = []
for i in range(0, len(nums)):
if nums[i] == result:
record_numbers.append(nums[i])
return record_numbers[0]
class Solution:
def majorityElement(self, nums):
majority_count = len(nums)//2
for num in nums:
count = sum(1 for elem in nums if elem == num)
if count > majority_count:
return num
class Solution:
def majorityElement(self, nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
def bracket(data):
return data
if __name__ == '__main__':
# 不带括号调用的结果:, a是整个函数体,是一个函数对象,不须等该函数执行完成
a = bracket
print a
# 带括号调用的结果:6, b是函数执行后返回的值6, 须等该函数执行完成的结果
b = bracket(6)
print b
import random
class Solution:
def majorityElement(self, nums):
majority_count = len(nums)//2
while True:
candidate = random.choice(nums) #注意random.choice用法
#choice() 方法返回一个列表,元组或字符串的随机项
if sum(1 for elem in nums if elem == candidate) > majority_count:
return candidate
class Solution:
def majorityElement(self, nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate