题解 | #牧场里的编号顺序#
牧场里的编号顺序
https://www.nowcoder.com/practice/6741b77f486a493da5258738323ddd3e?tpId=354&tqId=10589475&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj
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); } }
本题知识点分析:
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
高频面试算法题解 文章被收录于专栏
高频面试算法题解,每天一小步,人生一大步,跟着一起刷起来!