数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
用的方法包括:
- 如果有超过一半的,那么这个数与其他数互相抵消计算,最终肯定还有计数。每次只record一个数,如果这个数抵消完了,就记住最后抵消完的这个数,次数为1。
- 使用字典,有这个数就增加次数,最后直接看字典里的计数。
- 通过快排的partition来解决。(待更)
方法一 :时间复杂度O(n),空间O(1) ,较优
class Solution(object):
def majorityElement(self, nums):
if not nums:
return
count = 0
result = nums[0]
for i in nums:
if i == result:
count += 1
else:
count -= 1
if count == 0:
result = i
count += 1
if count != 0:
return result
else:
return
方法二
class Solution(object):
def majorityElement(self, nums):
if not nums:
return
b = {}
for i in nums:
if i not in b:
b[i] = 1
else:
b[i] += 1
if b[i] > 0.5*len(nums):
return i
for j in b:
if b[j] > 0.5*len(nums):
return j
return