题解 | #牧场里的编号顺序#
牧场里的编号顺序
https://www.nowcoder.com/practice/6741b77f486a493da5258738323ddd3e
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param ids int整型一维数组 * @param n int整型 * @return int整型 */ public int longestConsecutive (int[] ids, int n) { // write code here 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); } }
知识点:
1.双指针
2.数组遍历
3.函数库Math.max
解题分析:
1.慢指针用于判断左边界
2.快指针用于判断右边界
3.循环条件是fast<=ids.length-1也就是n-1
4.如果符合连续递增,那么右边界一直递增
5.如果不符合了,也就是断开了,那么计算这时候的长度,然后将fast的位置赋值给slow,然后再把fast的位置改为slow+1
6.最后返回的时候再取出length和fast-slow中较大的那个,因为可能有多个连续区间,我们要取最大的。
编程语言:
Java