题解 | #寻找最合适的生育区域#
寻找最合适的生育区域
https://www.nowcoder.com/practice/c183c254a5c94b9da341fb27fb3caf99
题目考察的知识点
考察双指针算法
题目解答方法的文字分析
采用双指针,快指针一直向后遍历,只有说两个指针之间的区域都满足条件的时候,count增加作为计数,当出现不满足情况的时候,更新最大值res,并将慢指针更新。
本题解析所用的编程语言
使用Java代码解答
完整且正确的编程代码
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param heights int整型一维数组
* @param k int整型
* @return int整型
*/
public int findMaxRangeWithinThreshold (int[] heights, int k) {
int result = 1;
int count = 1;
for (int i = 0, j = 1; j < heights.length; j++) {
if (Math.abs(heights[i] - heights[j]) < k) { //符合的区间
count++;
} else {
result = Math.max(result, count);
count = 1; //重新计数
}
i = j; //更新慢指针
}
return Math.max(result, count);
}
}

