2020.10.28每日复习
942.增减字符串匹配
分析
- 同时维护一个最大值和一个最小值,当为“I”时,说明后一个数大于此数,则令此时的数等于现在所维护的最小值。当为“D”,说明后一个数小于此数,则令此时的数等于现在所维护的最大值。
class Solution {
public int[] diStringMatch(String S) {
int N = S.length();
int[] res = new int[N + 1];
char[] ch = S.toCharArray();
int a = 0, b = N;//a为所维护的最小值,b为所维护的最大值
for(int i = 0; i < N; i++) {
if(ch[i] == 'I') {
res[i] = a;
a++;//维护的最小值+1
}else {
res[i] = b;
b--;//维护的最大值-1
}
}
res[N] = a;//数组最后一个数为所剩下的那个数
return res;
}
}
1025.除数博弈
分析
- 当N为奇数时,Alice(先手)必败;当N为偶数时,Alice必胜
- 当N=1时,Alice败;当N=2时,Alice胜;
- 当N<=k时成立;
- 当N=k+1时:
- (1)如果 k 为偶数,则 k + 1为奇数,x是 k + 1 的因数,只可能是奇数,而奇数减去奇数等于偶数,且 k + 1 - x≤k,故轮到 Bob 的时候都是偶数。而根据我们的猜想假设 N≤k 的时候偶数的时候先手必胜,故此时无论 Alice 拿走什么,Bob 都会处于必胜态,所以 Alice 处于必败态。
- (2)如果 k 为奇数,则 k+1 为偶数,x 可以是奇数也可以是偶数,若 Alice 减去一个奇数,那么 k + 1 - x 是一个小于等于 k 的奇数,此时 Bob 占有它,处于必败态,则 Alice 处于必胜态。
class Solution {
public boolean divisorGame(int N) {
return N % 2 == 0;
}
}
1237.找出给定方程的正整数解
分析
- 用二分法,依次遍历x和y,将符合条件的存入数组
/*
* // This is the custom function interface.
* // You should not implement it, or speculate about its implementation
* class CustomFunction {
* // Returns f(x, y) for any given positive integers x and y.
* // Note that f(x, y) is increasing with respect to both x and y.
* // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
* public int f(int x, int y);
* };
*/
class Solution {
public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
List<List<Integer>> res = new ArrayList<>();
int yr = 1000;
for(int x = 1; x <= 1000; x++) {
int yl = 1;
if(customfunction.f(x, 1) > z) break;//若x和1的运算都大于z,由单调递增得,后面的肯定都大于z,则直接跳出循环
if(customfunction.f(x, yr) < z) continue;//若x和目前最大的y的运算都小于z,则说明在当前的y中没有符合条件的,直接进入下一个x
while(yl <= yr) {
int mid = yl + (yr - yl) / 2;
int temp = customfunction.f(x, mid);
if(temp < z) yl = mid + 1;
else if(temp > z) yr = mid - 1;
else {
List<Integer> list = new ArrayList<>();
list.add(x);
list.add(mid);
res.add(list);
yr = mid - 1;
break;
}
}
}
return res;
}
}