publicclassSolution{publicList<Integer>majorityElement(int[]nums){List<Integer>ret=newLinkedList<Integer>();intc1=0,c2=0,n1=0,n2=0;for(intnum:nums){if(num==c1)n1++;elseif(num==c2)n2++;elseif(n1==0){c1=num;n1++;}elseif(n2==0){c2=num;n2++;}else{n1--;n2--;}}intcount1=0;intcount2=0;for(intnum:nums){if(num==c1)count1++;// must be else if [0,0,0]elseif(num==c2)count2++;}if(count1>nums.length/3)ret.add(c1);if(count2>nums.length/3)ret.add(c2);returnret;}}
classSolution(object):defmajorityElement(self,nums):""" :type nums: List[int] :rtype: List[int] """ifnotnums:returnnumsret=[]# two candidatesn1=0n2=0# appear times for themc1=0c2=0foriinnums:# order is importantifn1==i:c1+=1elifn2==i:c2+=1elifc1==0:c1=1n1=ielifc2==0:c2=1n2=ielse:c1-=1c2-=1# count the appear time of two candidatesifc1!=0andnums.count(n1)>len(nums)/3:ret.append(n1)ifc2!=0andnums.count(n2)>len(nums)/3:ret.append(n2)returnret