Lintcode "Majority number III"

Source: Internet
Author: User
Tags lintcode

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.