Skip to content

Latest commit

 

History

History
40 lines (34 loc) · 803 Bytes

169.md

File metadata and controls

40 lines (34 loc) · 803 Bytes

169. Majority Element

题目链接

python方法,利用字典

class Solution(object):
    def majorityElement(self, nums):
		judge = 0.5
		num_dict={}
		for i in range(len(nums)):
			if nums[i] in num_dict:
				num_dict[nums[i]] = num_dict[nums[i]] + 1
			else:
				num_dict[nums[i]] = 1
		for num, counts in num_dict.items():
			if counts*1.0/len(nums) > judge: 
				return num
				

O(n) time O(1) space fastest solution 的算法

class Solution(object):
    def majorityElement(self, nums):
		major = nums[0]
		count = 1
		for i in range(1, len(nums)):
			if count == 0:
				major = nums[i]
				count = 1
			elif major == nums[i]:
				count = count + 1
			else:
				count = count - 1
		return major