题解 | #牧场里的编号顺序#
牧场里的编号顺序
https://www.nowcoder.com/practice/6741b77f486a493da5258738323ddd3e
知识点:双指针
思路:
- 将参数
ids
的类型从int[]
改为List<Integer>
,以符合Java的列表方式。如果你仍然希望使用数组,请将int[]
修改回去。 - 将
ids.length
修改为参数n
,以适应传入的元素数量。 - 替换
Math.max(length, fast - slow)
中的fast - slow
为当前循环的fast - slow
,以确保计算正确的最大长度。
编程语言:java
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param ids int整型一维数组 * @param n int整型 * @return int整型 */ public int longestConsecutive (int[] ids, int n) { int slow = 0; int fast = 1; int length = 0; //循环遍历 while(fast<=ids.length-1){ if(ids[fast]>ids[fast-1]){ fast++; }else{ length = Math.max(length,fast-slow); slow = fast; fast = slow+1; } } //返回最大值 return Math.max(length,fast-slow); } }