https://leetcode.cn/problems/task-scheduler-ii/
这道题一开始我模拟做,超时了😂,参考别人的题解,发现一些步骤上可以简化的。
class Solution {
public:
long long taskSchedulerII(vector<int>& tasks, int space) {
unordered_map<int, long long> hash;
long long ans = 0;
for (auto & x : tasks) {
// 若没有做过同一类型的任务,或者中间间隔天数满足 space,ans 结果加一天
if (hash[x] == 0 || ans - hash[x] > space) {
ans++;
// 否则,将 ans 赋值为上一次同一类型的任务的日子 + space 时间间隔 + 1
} else {
ans = hash[x] + space + 1;
}
// 最后将该类型任务日子变为当前的 ans 的日子
hash[x] = ans;
}
return ans;
}
};
class Solution {
public:
long long taskSchedulerII(vector<int>& tasks, int space) {
unordered_map<int, long long> hash;
long long ans = 0;
for (auto & x : tasks) {
ans++; // 完成该任务,天数+1
if (hash[x] != 0) {
ans = max(ans, hash[x] + space + 1); // 看看是否要间隔 space 天
}
hash[x] = ans; // 记录完成任务的时间
}
return ans;
}
};
https://leetcode.cn/problems/minimum-replacements-to-sort-the-array/
因为最后的数组要满足递增,所以最后一个不要拆!如果最后一个拆了,前面拆的次数也会变多。
从后往前遍历,维护拆完后的数组中的最小值 minValue,
若 nums[i] > minValue,对 nums[i] 进行拆分,怎么拆?
拆出来的最大值 >= minValuek - 1拆出来的最小值 =
⌊
n
u
m
s
[
i
]
k
⌋
\lfloor \frac{nums[i]}{k} \rfloor
⌊knums[i]⌋class Solution:
def minimumReplacement(self, nums: List[int]) -> int:
ans = 0
minValue = nums[-1] # 最后一个不用拆
for x in nums[-2::-1]: # 从倒数第二个开始遍历
if x > minValue:
k = ceil(x / minValue) # 上取整
ans += k - 1
minValue = x // k
else:
minValue = x
return ans