Majority Element II
Description:
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Find it.
Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.
Challenge
O(n) time and O(1) extra space.
Notice
There is only one majority number in the array.
Code:
class Solution:
"""
@param: nums: a list of integers
@return: The majority number that occurs more than 1/3
"""
def majorityNumber(self, nums):
# write your code here
if nums == None:
return []
cnt1, cnt2, tmp1, tmp2 = 0, 0, 0, 0
for i in range(len(nums)):
if nums[i] == tmp1:
cnt1 += 1
elif nums[i] == tmp2:
cnt2 += 1
elif cnt1 == 0:
cnt1 = 1
tmp1 = nums[i]
elif cnt2 == 0:
cnt2 = 1
tmp2 = nums[i]
else:
cnt1-=1
cnt2-=1
if nums.count(tmp1) >(1/3)*len(nums):
return tmp1
else:
return tmp2