5173. 质数排列
请你帮忙给从 1 到 n 的数设计排列方案,使得所有的「质数」都应该被放在「质数索引」(索引从 1 开始)上;你需要返回可能的方案总数。
让我们一起来回顾一下「质数」:质数一定是大于 1 的,并且不能用两个小于它的正整数的乘积来表示。
由于答案可能会很大,所以请你返回答案 模 mod 10^9 + 7 之后的结果即可。
示例 1:
输入:n = 5
输出:12
解释:举个例子,[1,2,5,4,3] 是一个有效的排列,但 [5,2,3,4,1] 不是,因为在第二种情况里质数 5 被错误地放在索引为 1 的位置上。
示例 2:
输入:n = 100
输出:682289015
提示:
1 <= n <= 100
先找出2-n上质数的个数,分别求质数和非质数的排列组合(int类型与long类型运算,int会转型成long类型)
int mod = (int)1e9+7;
// 求n的阶乘
long help(int n) {
long res = 1;
for (int i = 1; i <= n; i++) {
res = res * i % mod;
}
return res;
}
// 找出2-n质数的个数
int numPrimeArrangements(int n) {
if(n == 1) return 1;
int cnt = 0;
// 数组arr:如果第i个位置为1则不是质数,第i个位置为0则为质数
int[] arr = new int[n + 1];
Arrays.fill(arr, 0);
for (int i = 2; i <= n; i++) {
if (arr[i] == 0) {
cnt++;
for (int j = i + i; j <= n; j += i) {
arr[j] = 1;
}
}
}
return (int)(help(n - cnt) * help(cnt) % mod);
}
5174. 健身计划评估
你的好友是一位健身爱好者。前段日子,他给自己制定了一份健身计划。现在想请你帮他评估一下这份计划是否合理。
他会有一份计划消耗的卡路里表,其中 calories[i] 给出了你的这位好友在第 i 天需要消耗的卡路里总量。
计划的统计周期通常是 k 天,你需要计算他在每一段连续的 k 天内消耗的总卡路里 T:
- 如果 T < lower,那么这份计划相对糟糕,并失去 1 分;
- 如果 T > upper,那么这份计划相对优秀,并获得 1 分;
- 否则,这份计划普普通通,分值不做变动。
请返回统计完所有 calories.length 天后得到的总分作为评估结果。
注意:总分可能是负数。
示例 1:
输入:calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
输出:0
解释:calories[0], calories[1] < lower 而 calories[3], calories[4] > upper, 总分 = 0.
示例 2:
输入:calories = [3,2], k = 2, lower = 0, upper = 1
输出:1
解释:calories[0] + calories[1] > upper, 总分 = 1.
示例 3:
输入:calories = [6,5,0,0], k = 2, lower = 1, upper = 5
输出:0
解释:calories[0] + calories[1] > upper, calories[2] + calories[3] < lower, 总分 = 0.
窗口法:
public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
int ans = 0, sum = 0, left = 0, right = 0;
for(int i = 0; i < calories.length; i++){
sum += calories[right];
// 达到窗口大小
if (right - left + 1 == k) {
ans += sum > upper ? 1 : 0;
ans += sum < lower ? -1 : 0;
sum -= calories[left++];
}
right++;
}
return ans;
}