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); } }
编程语言是Java。
这道题考察的知识点是数组和循环的运用。给定一个整数数组ids和一个整数n,要求计算在ids数组中找到的最长连续递增序列的长度。
代码的文字解释如下:
- slow(慢指针)、fast(快指针)和length(最长连续序列的长度),并初始化为0。
- 循环遍历数组ids。循环的条件是fast小于等于ids数组的长度减去1。
- 在循环中,判断当前位置的元素是否大于前一个位置的元素。如果是,则将fast指针右移一位。
- 如果当前位置的元素不大于前一个位置的元素,说明出现了断点,需要更新最长连续序列的长度,并将slow指针和fast指针更新为当前位置的下一个位置。
- 循环结束后,再次更新最长连续序列的长度,取当前长度length和fast-slow的较大值。
- 返回最长连续序列的长度。