Skip to content

Commit

Permalink
Create online-election.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 23, 2018
1 parent a61b88f commit a5e7006
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions C++/online-election.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Time: ctor: O(n)
// q: O(logn)
// Space: O(n)

class TopVotedCandidate {
public:
TopVotedCandidate(vector<int> persons, vector<int> times) {
int lead = -1;
unordered_map<int, int> count;
for (int i = 0; i < persons.size(); ++i) {
lookup_[times[i]] = persons[i];
}
for (auto& kvp : lookup_) {
if (++count[kvp.second] >= count[lead]) {
lead = kvp.second;
}
kvp.second = lead;
}
}

int q(int t) {
return prev(lookup_.upper_bound(t))->second;
}

private:
map<int, int> lookup_;
};

/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate obj = new TopVotedCandidate(persons, times);
* int param_1 = obj.q(t);
*/

0 comments on commit a5e7006

Please sign in to comment.