双指针问题
双指针思路(求最长连续子数组):右指针一直向右移动,当在左右指针范围内的补种的数量小于死去的数量则向右移动左指针。
package test;
/**
* Description:
* Author: Mr.Zhao
* Create Date Time: 2022/10/21 21:19.
* Update Date Time:
*/
import java.util.Scanner;
=============================================================
第一种解法
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//总数
int N = Integer.parseInt(scanner.nextLine());
//未成活的树
int M = Integer.parseInt(scanner.nextLine());
// 未成活的具体树木---用数组表示
String[] Ms = scanner.nextLine().split(" ");
int[] ints_M = new int[M];
//补种的树木K
int K = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < Ms.length; i++) {
ints_M[i] = Integer.parseInt(Ms[i]);
}
int start=1;
int end=1;
int max=0;
int temp=0;
while (start <= end && start <= N) {
int same=0;
for (int i = start; i <=end; i++) {
for (int j = 0; j < ints_M.length; j++) {
if (i == ints_M[j]) {
same++;
}
}
}
if (end <= N && same <= K) {
temp = end-start+1;
max = Math.max(max, temp);
end =end+1;
} else {
start++;
if (start <= end && same <= K) {
temp = end-start+1;
max = Math.max(max, temp);
}
}
}
System.out.println(max);
}
}
==========================================================================
第二种解法
public class Solution {
public int computeNum(String str) {
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '0') {
sum++;
}
}
return sum;
}
public int maxSubArrayLen() {
// 数据初始化
Scanner sc = new Scanner(System.in);
int N = Integer.valueOf(sc.nextLine());
int M = Integer.valueOf(sc.nextLine());
String[] s = sc.nextLine().split(" ");
int K = Integer.valueOf(sc.nextLine());
String[] arr = new String[N];
// 赋值
for (int i = 0; i < N; i++) {
arr[i] = "1";
}
for (String item : s) {
arr[Integer.valueOf(item) - 1] = "0";
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < N; i++) {
buffer.append(arr[i]);
}
// 逻辑处理
int left=0;
int right=0;
int maxLength = Integer.MIN_VALUE;
String sum="";
for (right = 0; right < N; right++) {
// 条件
sum = sum + arr[right];
int total = computeNum(sum);
while (left <= right && total > K) {
maxLength = Math.max(maxLength, right - left);
left++;
sum = buffer.substring(left, right+1);
total = computeNum(sum);
}
}
return maxLength>right-left?maxLength:right-left;
}
}
浙公网安备 33010602011771号