Edit: In Solution 2, if I use upper_bound function instead of the menber function of multiset, time limit exceeded will alse be reported. So, I think the difference if upper_bound function and the member function upper_bound of multiset results in the situation. In that case, where is the difference between the two functions.
-------------------------------------------------------------------------------------------------------
Previous question:
When I solve the #870 of leetcode(
https://leetcode.com/problems/advantage-shuffle/), I meet with a question about the upper_bound function.
The question is to rearrange nums1 to make the total number of i satisfying nums1[i] > nums2[i] as large as possible.
Here is my code using list:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// Solution 1
// sort nums1 first and save it in list for fast delete, then find the first
// element that is greater than nums2[i] and delete it in the list. If not find,
// using the head of list and delete it.
vector<int> Solution::advantageCount(vector<int>& nums1, vector<int>& nums2)
{
sort(nums1.begin(), nums1.end());
list<int> tmp(nums1.begin(), nums1.end());
for (int i = 0; i < nums2.size(); ++i)
{
auto it = upper_bound(tmp.begin(), tmp.end(), nums2[i]);
if (it == tmp.end())
{
nums1[i] = tmp.front();
tmp.erase(tmp.begin());
}
else
{
nums1[i] = *it;
tmp.erase(it);
}
}
return nums1;
}
|
Code using multiset is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
// Solution 2
vector<int> advantageCount(vector<int>& a, vector<int>& b) {
multiset<int> s;
vector<int> v;
for (int i = 0; i < a.size(); i++) {
s.insert(a[i]);
}
for (int i = 0; i < b.size(); i++) {
// auto it = upper_bound(s.begin(), s.end(), b[i]); result in TLE
auto it = s.upper_bound(b[i]);
if (it != s.end()) {
v.push_back(*(it));
s.erase(it);
}
else {
v.push_back(*(s.begin()));
s.erase(s.begin());
}
}
return v;
}
|
I think the two solutions are different in the container that saves the sorted nums2. However, solution 1 reports time limit exceeded while solution 2 accepted. I doubt it results from the upper_bound function.
By the way, what will happen if the container input to unpper_bound is not sorted?
Thanks very much if you can help me.