标签:
Problem Definition:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Solution 1: 用字典来保存计数,简单粗暴
1 def majorityElement(self,nums): 2 d={} 3 for i in nums: 4 d.setdefault(i,0) 5 d[i]+=1 6 if d[i]>len(nums)/2: 7 return i
Solution 2: 1) 排序; 2) 中间往右一个位置的值即所求; 3)最快O(nlogn)
栗子:[1,2,3,4,4,4,4] [1,1,1,1,2,3]
1 def majorityElement(nums): 2 return sorted(nums)[len(nums)/2]
Solution 3: 投票,与前一元素相同投1,不同投-1,O(n)
1 def majorityElement(self,nums): 2 major,count,n=0,0,len(nums) 3 for i in nums: 4 if count==0: 5 major=i 6 count=1 7 else: 8 count+=(1 if i==major else -1) 9 return major
Solution 4: 不断地随机拿一个数,计数,看运气。
Solution 5: 位运算。(不知道为毛,当数组元素是负数的时候major会变成Long类型,整个就不work!!!!!!)
1 def majorityElement(self,nums): 2 major,mask,n=0,1,len(nums) 3 m=32 4 while m>0: 5 bc=0 6 for i in nums: 7 if i&mask: 8 bc+=1 9 if bc>n/2: 10 major|=mask 11 break 12 mask<<=1 13 m-=1 14 return major
标签:
原文地址:http://www.cnblogs.com/acetseng/p/4659993.html