826. Most Profit Assigning Work

这一题做出来了,但是不必要的步骤比较多,也就是不够简洁。
自己的做法:
按照利润由高到低排序,如果某一些排在后面的难度却更高,就删掉它们。
class Solution {
public:
int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
int workSz = profit.size();
if (workSz == 0)
return 0;
vector<pair<int, int>> works;
for (int i = 0; i < workSz; ++i)
works.push_back(make_pair(profit[i], difficulty[i]));
sort(works.begin(), works.end(), sortHelper);
int i = 1;
int nowDif = works[0].second;
for (int j = 1; j < workSz; ++j) {
if (works[j].second < nowDif) {
nowDif = works[j].second;
works[i++] = works[j];
}
}
//works.erase(works.begin()+i, works.end());必须删除范围
int endIdx = i;
sort(worker.begin(), worker.end(), greater<int>());
int maxProfit = 0;
i = 0;
int j = 0;
while (i < endIdx && j < worker.size()) {
while (i < endIdx && works[i].second > worker[j])
++i;
if (i == endIdx)
break;
maxProfit += works[i].first;
++j;
}
return maxProfit;
}
private:
static bool sortHelper(pair<int, int>& p1, pair<int, int>& p2) {
if (p1.first > p2.first)
return true;
else if (p1.first < p2.first)
return false;
else
return p1.second < p2.second;
}
};
方法二:
更加简洁的。
直接sort,没有删除这个步骤。如果有那种“难度更大,收益更低”的工作,可以直接略过,不必要处理。
class Solution {
public:
int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {
vector<pair<int, int>> jobs;
for (int i = 0; i < profit.size(); ++i)
jobs.push_back(make_pair(profit[i], difficulty[i]));
sort(jobs.begin(), jobs.end());
sort(worker.begin(), worker.end());
int i = jobs.size()-1;
int j = worker.size()-1;
int maxProfit = 0;
while (i >= 0 && j >= 0) {
while (i >= 0 && jobs[i].second > worker[j])
--i;
if (i < 0)
break;
maxProfit += jobs[i].first;
--j;
}
return maxProfit;
}
};
这个就简洁的多。这个代码量才是正常的。上面的有点多了
浙公网安备 33010602011771号