leetcode3250. 单调数组对的数目 I,仅需1s
题目:
https://leetcode.cn/problems/find-the-count-of-monotonic-pairs-i/description/
不为别的,只是记录下这个超过100%,而且比原先最快的快了一个量级
不知道咋分析,反正得出结论就是,变大不变,变小跟着变,最后一个数,如果是负数,直接为0,如果为正数,就是C(len+n取n)
两个解题时间如图:
1、使用加法计算C
class Solution {
public int countOfPairs(int[] nums) {
int jj = 0;
int len = nums.length;
for (int i = 1; i < len; i++) {
if (nums[i] - jj >= nums[i - 1]) {
jj = nums[i] - nums[i - 1];
nums[i] = nums[i - 1];
} else {
nums[i] -= jj;
if (nums[i] < 0) {
return 0;
}
}
}
return getAns(nums.length, nums[len - 1]);
}
//使用加法计算
private int getAns(int length, int num) {
long[] anss = new long[num + 1];
for (int i = 0; i < anss.length; i++) {
anss[i] = 1;
}
for (int i = 0; i < length; i++) {
for (int j = 1; j <= num; j++) {
anss[j] += anss[j - 1];
anss[j]%=1_000_000_007;
}
}
return (int) anss[num];
}
}
2、使用计算式计算C,因为存在1000_000_007,所以先约分
class Solution {
public int countOfPairs(int[] nums) {
int jj = 0;
int len = nums.length;
for (int i = 1; i < len; i++) {
if (nums[i] - jj >= nums[i - 1]) {
jj = nums[i] - nums[i - 1];
nums[i] = nums[i - 1];
} else {
nums[i] -= jj;
if (nums[i] < 0) {
return 0;
}
}
}
return getAns(nums.length, nums[len - 1]);
}
private int getAns(int length, int num) {
if (length <= num) {
return getAA(length, length + num);
} else {
return getAA(num, length + num);
}
}
//以下计算C(length取n)
private int getAA(int n, int length) {
if (n == 0) {
return 1;
}
int[] fenzi = new int[n];
for (int i = 0; i < n; i++) {
fenzi[i] = length - i;
}
for (int i = 1; i <= n; i++) {
int temp = i;
int j = 0;
while (temp > 1) {
int yue = getYue(temp, fenzi[j]);
temp /= yue;
fenzi[j] /= yue;
j++;
}
}
long ans = 1;
for (int i : fenzi) {
ans *= i;
ans %= 1000_000_007;
}
return (int) ans;
}
private int getYue(int t1, int t2) {
if (t1 == t2) {
return t1;
}
if (t1 > t2) {
return getYYY(t1, t2);
} else {
return getYYY(t2, t1);
}
}
private int getYYY(int t1, int t2) {
int t3 = t1 % t2;
if (t3 == 0) {
return t2;
}
return getYYY(t2, t3);
}
}