Sunday, July 20, 2014

TopCoder High School SRM 41 Level one - 250 pt - Majority Element solution

TopCoder High School SRM 41 Level one - 250 pt - Majority Element statement: http://community.topcoder.com/stat?c=problem_statement&pm=8137&rd=10788

TopCoder High School SRM 41 Level one - 250 pt - Majority Element editorial: http://community.topcoder.com/tc?module=Static&d1=hs&d2=match_editorials&d3=hs_srm41

TopCoder High School SRM 41 Level one - 250 pt - Majority Element solution: 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class MajorityElement {
    public: int findMajorityElement(vector <int> a) {
        int cnt=1, idx=0;
        sort(a.begin(), a.end());
        for(int i=1; i<a.size(); i++) {
            if(a[i]==a[i-1]) {
                cnt++; 
                if(cnt>a.size()/2) { idx=i; break; }
            }
            else cnt=1, idx=0;
        }
        if(idx==0 && a.size()>1) return -1;
        else return a[idx];
    }
};


No comments:

Post a Comment