Java 题解 | #牧场里的编号顺序#
牧场里的编号顺序
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 i = 0;
int ans = 1;
for (int j = 1; j < n; j++) {
if (ids[j] > ids[j - 1]) {
ans = Math.max(ans, j - i + 1);
} else {
i = j;
}
}
return ans;
}
}
使用的是Java语言。
该题考察的知识点包括数组的遍历和比较。
代码的文字解释如下:
- 遍历数组
ids,从第二个元素开始(索引为1):如果当前元素比前一个元素大,则表示仍处于连续序列中,更新最长连续序列的长度 ans 为当前位置减去起始位置加1,并与 ans 进行比较,取较大值。否则,当前元素不在连续序列中,更新起始位置 i 为当前位置。 - 返回最长连续序列的长度
ans。
美的集团公司福利 747人发布