本文主要是介绍229. Majority Element II 【M】【52】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
Hint:
- How many majority elements could it possibly have?
- Do you have a better hint? Suggest it!
Subscribe to see which companies asked this question
还是用抵消的办法
开始的参数是0.5,通过了
后来改成1 ,也通过了……
class Solution(object):def majorityElement(self, nums):a = '' #nums[0]b = '' #nums[1]ta = 0tb = 0l = len(nums)if l == 2:return list(set(nums))times = l/3for i in nums[:]:if i == a:ta += 1elif i == b:tb += 1elif ta <= 0:a = ita = 1elif tb <= 0:b = itb = 1else:ta -= 1tb -= 1res = []if nums.count(a) > times:res += a,if a != b and nums.count(b) > times:res += b,return res
这篇关于229. Majority Element II 【M】【52】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!