Last active
December 23, 2015 23:49
-
-
Save chuanying/6712152 to your computer and use it in GitHub Desktop.
[Microsoft] How to find if a number is present equal to or more than n/2 times in an array of size n?
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
/* Error!! | |
void helper(const vector<int> &vec, int pos, pair<int, int> &curr) { | |
for (int i = pos; i < vec.size(); ++i) { | |
if (curr.second == 0 || curr.first == vec[i] ) { | |
curr = make_pair(vec[i], curr.second + 1); | |
} else { | |
--curr.second; | |
} | |
} | |
} | |
int find_number(const vector<int> &vec) { | |
if (vec.empty()) { | |
return -1; // Error | |
} | |
pair<int, int> curr(vec[0], 1); | |
helper(vec, 2, curr); //ignore vec[1] | |
if (curr.second <= 0) { | |
curr = make_pair(vec[1], 1); | |
helper(vec, 2, curr); //ignore vec[0] | |
if (curr.second <= 0) { | |
curr = make_pair(vec[0], 1); //here vec[0] must equal to vec[1] | |
} | |
} | |
return curr.first; | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment