C++ customized comparison part 2
1 min readJan 3, 2021
Part 1 can be found here.
For part 2, I am going to focus on using some real examples to show how to use customized comparison. Those examples will be added to this article gradually.
Vector
1710. Maximum Units on a Truck
class Solution {
public:
int maximumUnits(vector<vector<int>>& a, int truckSize) {
sort(a.begin(), a.end(),
[](const vector<int>& lhs, const vector<int>& rhs) {
return lhs[1] > rhs[1];
});
int ret = 0, used = 0;
for (int i = 0; i < a.size() && truckSize > 0; ++i) {
used = min(truckSize, a[i][0]);
ret += used*a[i][1];
truckSize -= used;
}
return ret;
}
};
Or we can use auto
class Solution {
public:
int maximumUnits(vector<vector<int>>& a, int truckSize) {
sort(a.begin(), a.end(),
[](const auto& lhs, const auto& rhs) {
return lhs[1] > rhs[1];
});
int ret = 0, used = 0;
for (int i = 0; i < a.size() && truckSize > 0; ++i) {
used = min(truckSize, a[i][0]);
ret += used*a[i][1];
truckSize -= used;
}
return ret;
}
};
Thanks for reading and hope it helps.