Approach
This problem is simple, maintain unordered_map for the itemID, for each itermID maintain userId mapping to the bid, and also store this pair inside a unordered_set for fast query. Need to chekc if hte itemId and userId is still inside the hashmap (get 1 WA on this … ) .
Code
class AuctionSystem {
public:
unordered_map<int, set<pair<int,int>, greater<pair<int,int>>> > mp; // itemId ->
unordered_map<int, unordered_map<int, int> > mp2; // itemId ->
AuctionSystem() {
mp.clear();
mp2.clear();
}
void addBid(int userId, int itemId, int bidAmount) {
auto& st = mp[itemId];
auto& st2 = mp2[itemId];
if(st2.count(userId)) {
int bid = st2[userId];
st.erase({bid, userId});
st.insert({bidAmount, userId});
st2[userId] = bidAmount;
} else {
st.insert({bidAmount, userId});
st2[userId] = bidAmount;
}
}
void updateBid(int userId, int itemId, int newAmount) {
auto& st = mp[itemId];
auto& st2 = mp2[itemId];
int bid = st2[userId];
st.erase({bid, userId});
st.insert({newAmount, userId});
st2[userId] = newAmount;
}
void removeBid(int userId, int itemId) {
auto& st = mp[itemId];
auto& st2 = mp2[itemId];
int bid = st2[userId];
st.erase({bid, userId});
st2.erase(userId);
}
int getHighestBidder(int itemId) {
return mp.count(itemId) && mp[itemId].size() != 0 ? mp[itemId].begin()->second : -1;
}
};