Problem Definition:
Given an array of size n, find the majority element. The majority element is the element, the appears more than times ⌊ n/2 ⌋ .
Assume that the array was non-empty and the majority element always exist in the array.
Solution 1: Use a dictionary to save the count, simple rough
1 def majorityelement (self,nums): 2 d={}3for in nums:4 d.setdefault (i,0) 5 d[i]+=16 if d[i]>len (nums)/2:7 return I
Solution 2:1) Sort, 2) the value of the middle to the right position is the desired one; 3) Fastest O (nlogn)
Chestnuts: [4, 4,4,4] [1,1,1,1, 2,3]
1 def majorityelement (nums): 2 return Sorted (nums) [Len (Nums)/2]
Solution 3: Vote, same as the previous element cast 1, different cast -1,o (n)
1 defmajorityelement (self,nums):2major,count,n=0,0,len (nums)3 forIinchNums:4 ifcount==0:5Major=I6Count=17 Else:8count+= (1ifI==majorElse-1)9 returnMajor
Solution 4: Constantly randomly take a number, count, see luck.
Solution 5: Bitwise operation. (not known as the fur, when the array element is negative, major will become a long type, the whole does not work!!!!!!)
1 defmajorityelement (self,nums):2major,mask,n=0,1, Len (nums)3M=324 whileM>0:5Bc=06 forIinchNums:7 ifi&Mask:8Bc+=19 ifBc>n/2:Tenmajor|=Mask One Break AMask<<=1 -M-=1 - returnMajor
leetcode#169 Majority Element