Skip to content

Instantly share code, notes, and snippets.

@chuanying
Last active December 23, 2015 23:49
Show Gist options
  • Save chuanying/6712152 to your computer and use it in GitHub Desktop.
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?
/* 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