Given an integer array of size n, find all elements this appear more than times ⌊ n/3 ⌋
. The algorithm should run in linear time and in O (1) space.
Ideas:
"Leetcode 169" Majority Element of the expansion, this call is more than one-third times the number of occurrences, moving our brains to think, such a number will exist a few, of course, 2. So, then the method of the previous question to do, but this time to cast two votes, and finally have to check whether the two poll results are not really satisfied are more than One-third, because this topic is nothing guaranteed, so the answer may be 0, one, 2.
C++:
1 classSolution {2 Public:3vector<int> Majorityelement (vector<int>&nums) {4vector<int>ret;5 6 intLen =nums.size ();7 if(len = =0)8 returnret;9 Ten intm =0, n =0, CM =0, CN =0; One for(inti =0; i < Len; i++) A { - intval =Nums[i]; - if(M = =val) thecm++; - Else if(n = =val) -cn++; - Else if(cm = =0) + { -m =Val; +CM =1; A } at Else if(CN = =0) - { -n =Val; -CN =1; - } - Else in { -cm--; tocn--; + } - } the *CM = CN =0; $ Panax Notoginseng for(inti =0; i < Len; i++) - { the if(Nums[i] = =m) +cm++; A Else if(Nums[i] = =N) thecn++; + } - $ if(CM *3>len) $ Ret.push_back (m); - if(CN *3>len) - ret.push_back (n); the - returnret;Wuyi } the};
Python:
1 classSolution:2 #@param {integer[]} nums3 #@return {integer[]}4 defmajorityelement (Self, nums):5m, n, cm, CN =0, 0, 0, 06RET = []7 8 forValinchNums:9 ifm = =Val:TenCM = cm + 1 One elifn = =Val: ACN = CN + 1 - elifCM = =0: -m =Val theCM = 1 - elifCN = =0: -n =Val -CN = 1 + Else: -CM = Cm-1 +CN = Cn-1 A atCM, CN =0, 0 - - forValinchNums: - ifm = =Val: -CM = cm + 1 - elifn = =Val: inCN = CN + 1 - to ifCM * 3 >Len (nums): + ret.append (m) - ifCN * 3 >Len (nums): the ret.append (n) * $ returnRet
"Leetcode 229" Majority Element II