Created
April 29, 2015 22:27
-
-
Save walkingtospace/80fc2f995431226bfe7b to your computer and use it in GitHub Desktop.
Find majority(improved)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//assume object is int | |
int findMajority(vector<int> input) { | |
vector<int> temp; | |
if (input.size() == 0) return NOMAJORITY; | |
else if (input.size() == 1) return input[0]; | |
else if (input.size() == 2) { | |
if (input[0] == input[1]) return input[0]; | |
else return NOMAJORITY; | |
} | |
if (input.size() % 2 == 0) { | |
for (int i = 1; i < input.size(); i += 2) { | |
if (input[i] == input[i - 1]) { | |
temp.push_back(input[i]); | |
} | |
} | |
} | |
else { | |
for (int i = 1; i < input.size(); i += 2) { | |
if (input[i] == input[i - 1]) { | |
temp.push_back(input[i]); | |
} | |
} | |
temp.push_back(input[input.size()-1]); | |
} | |
int majority = findMajority(temp); | |
if (countNum(input, majority) > input.size() / 2) return majority; | |
else return NOMAJORITY; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment