Based on bucketing and "Majority number I".
classSolution {Pair<int,int> MajorityNumber0 (vector<int> &num) { intCount =0; intRET =0; for(inti =0; I < num.size (); i + +) { if(Count = =0) {ret=Num[i]; Count=1; Continue; } if(ret! = Num[i]) Count--; Else if(ret = = Num[i]) Count + +; } //Find Count intCNT =0; for(auto V:num)if(v = ret) cnt + +; returnMake_pair (ret, CNT); } Public: /** * @param nums:a List of integers * @param k:as described * @return: the majority number*/ intMajoritynumber (vector<int> Nums,intk) {intn =nums.size (); Auto mm=minmax_element (Nums.begin (), Nums.end ()); intMINV = *mm.first, MAXV = *Mm.second; intDist = ((MAXV-MINV)/k) +1; Vector<pair<int, vector<int>>> bkt (k +1, Make_pair (0, vector<int>())); for(Auto v:nums) {intInx = (V-MINV)/Dist; Bkt[inx].first++; Bkt[inx].second.push_back (v); } intTGT = n/K; for(Auto &p:bkt) { if(P.first >TGT) {Auto RP=MajorityNumber0 (P.second); if(Rp.second >TGT) { returnRp.first; } } } return 0; }};
And yes, the MAJORITYNUMBER0 () call can is inlined in the pass 1. That'll make it O (k) space. One solution online with HashMap are very similar with the bucketing idea here.
Lintcode "Majority number III"