文章目录
-
- [5641. 卡车上的最大单元数(贪心)](https://leetcode-cn.com/problems/maximum-units-on-a-truck/)
- [5642. 大餐计数(枚举 + 哈希表)](https://leetcode-cn.com/problems/count-good-meals/)
- [5643. 将数组分成三个子数组的方案数(前缀和 + 双指针)](https://leetcode-cn.com/problems/ways-to-split-array-into-three-subarrays/)
- [5644. 得到子序列的最少操作次数(贪心 + 最长上升子序列)](https://leetcode-cn.com/problems/minimum-operations-to-make-a-subsequence/)
5641. 卡车上的最大单元数(贪心)
class Solution {
public:
int maximumUnits(vector<vector<int>>& b, int m) {
sort(b.begin(), b.end(), [](vector<int> a, vector<int> b){
// lambda表达式
return a[1] > b[1];
});
int res = 0;
for(int i = 0;i < b.size() && m > 0; i ++ )
{
int cur = min(b[i][0],m);
res += cur * b[i][1];
m -= cur;
}
return res;
}
};
5642. 大餐计数(枚举 + 哈希表)
分析:
a[i] + a[j] = 2 k 2^{k} 2k,固定 j,即转化为 1~j中有多少个数满足 2 k − a [ j ] 2^{k} - a[j] 2k−a[j],使用哈希表。其中 2 k 2^{k} 2k 直接枚举,时间复杂度O(22n)
class Solution {
public:
int countPairs(vector<int>& d) {
unordered_map<int,int> hash;
int res = 0, mod = 1e9 + 7;
for(auto x : d)
{
for(int i = 0;i <= 21; i ++ ) // 2的幂直接枚举,枚举到21!
{
int t = (1 << i) - x;
if(hash.count(t)) res = (res + hash[t]) % mod;
}
hash[x] ++;
}
return res;
}
};
5643. 将数组分成三个子数组的方案数(前缀和 + 双指针)
分析:
存在单调性,两个双指针合在一起,边界不好写!时间复杂度O(n)
class Solution {
public:
int waysToSplit(vector<int>& nums) {
int n = nums.size();
vector<int> s(n + 1);
for(int i = 1;i <= n ;i ++ ) s[i] = s[i - 1] + nums[i - 1]; // 前缀和下标从1开始
int res = 0, mod = 1e9 + 7;
for(int i = 3, j = 2, k = 2;i <= n; i ++ )
{
while(s[n] - s[i - 1] < s[i - 1] - s[j - 1]) j ++ ;
while(k + 1 < i && s[i - 1] - s[k] >= s[k]) k ++ ;
if(j <= k && s[n] - s[i - 1] >= s[i - 1] - s[j - 1] && s[i - 1] - s[k - 1] >= s[k - 1])
res = (res + k - j + 1) % mod;
}
return res;
}
};
5644. 得到子序列的最少操作次数(贪心 + 最长上升子序列)
分析:
最长公共子序列转化为最长上升子序列,贪心求最长上升子序列的长度,AcWing 896. 最长上升子序列 II【贪心,二分优化】 ,时间复杂度O(nlogn)
class Solution {
public:
int minOperations(vector<int>& target, vector<int>& arr) {
unordered_map<int,int> pos;
for(int i = 0; i< target.size();i ++ )
pos[target[i]] = i;
vector<int> a;
for(auto x : arr)
if(pos.count(x))
a.push_back(pos[x]);
// 贪心求最长上升子序列长度,模板背过!
int len = 0;
vector<int> q(a.size() + 1);
for(int i = 0;i < a.size(); i++ )
{
int l = 0, r = len;
while(l < r){
int mid = l + r + 1>> 1;
if(q[mid] < a[i]) l = mid;
else r = mid - 1;
}
len = max(len, r + 1);
q[r + 1] = a[i];
}
return target.size() - len;
}
};