multiset 与 priority_queue
联系: 可以实现 大小顶堆;
区别: 删除元素时,multiset 会把相同元素值都删除!!
代码 1 :(Accept)
class Solution {
public:
int findMaximizedCapital(int k, int W, vector<int>& Profits, vector<int>& Capitals) {
multimap<int,int> mp;
for (int i = 0; i < Capitals.size(); ++i)
mp.insert (make_pair(Capitals[i], Profits[i]));
priority_queue<int> heap;
while (k--){
for (auto iter = mp.begin(); iter != mp.end();){
if (iter->first <= W){
heap.push(iter->second);
iter = mp.erase (iter);
}
else
break;
}
if (!heap.empty()){
W += heap.top();
heap.pop();
}
else
break;
}
return W;
}
};
代码 2 : (Wrong Answer)
class Solution {
public:
int findMaximizedCapital(int k, int W, vector<int>& Profits, vector<int>& Capitals) {
multimap<int,int> mp;
for (int i = 0; i < Capitals.size(); ++i)
mp.insert (make_pair(Capitals[i], Profits[i]));
multiset<int> st;
while (k--){
for (auto iter = mp.begin(); iter != mp.end();){
if (iter->first <= W){
st.insert (iter->second);
iter = mp.erase (iter);
}
else
break;
}
if (!st.empty()){
W += *st.rbegin();
st.erase (*st.rbegin()); // st.erase (--st.end()); 这样写就对了
}
else
break;
}
return W;
}
};