给定一个未经排序的整数数组,找到最长且连续递增的子序列,并返回该序列的长度。
连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[ i ] < nums[i + 1] ,那么子序列 [nums[ l ], nums[l + 1], …, nums[r - 1], nums[ r ]] 就是连续递增子序列。
0 ≤ nums.length ≤104
−109 ≤ nums[ i ] ≤ 109
示例1:
输入:nums = [1, 3, 5, 4, 7]
输出:3
解释:最长连续递增序列是 [1, 3, 5], 长度为3。
尽管 [1, 3, 5, 7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。
示例2:
输入:nums = [2, 2, 2, 2, 2]
输出:1
解释:最长连续递增序列是 [2], 长度为1。
思路分析:
题目要求我们找的子序列是 连续 的,并且子序列里的元素要求严格单调递增。在遍历的时候,从第 2 个元素开始;
如果当前遍历到的元素比它左边的那一个元素要严格大,「连续递增」的长度就加 1;
否则「连续递增」的起始位置就需要重新开始计算。这里给出两个参考代码。
- 滑动窗口和双指针;
- 动态规划;
参考代码 1:
public class 最长连续递增序列 {
public static int findLengthOfLCIS1(int[] nums) {
int len = nums.length;
int res = 0;
int left = 0;
int right = 0;
// 循环不变量 [left..right) 严格单调递增
while (right < len) {
if (right > 0 && nums[right - 1] >= nums[right]) {
left = right;
}
right++;
res = Math.max(res, right - left);
}
return res;
}
// 动态规划
public static int findLengthOfLCIS2(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int maxLen = 1;
int currentLen = 1;
// f(i)表示以当前元素结尾的最长连续递增序列长度:如果当前元素大于上一元素f(i) = f(i-1) + 1;否则f(i) = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] < nums[i]) {
currentLen++;
} else {
maxLen = currentLen > maxLen ? currentLen : maxLen;
currentLen = 1;
}
}
return maxLen;
}
public static void main(String[] args) {
int[] nums = {1, 3, 5, 4, 7};
int[] nums1 = {2, 2, 2, 2, 2};
System.out.println(findLengthOfLCIS1(nums));
System.out.println(findLengthOfLCIS1(nums1));
System.out.println(findLengthOfLCIS2(nums));
System.out.println(findLengthOfLCIS2(nums1));
}
}
复杂度分析:
时间复杂度:O(N),其中 N 是数组 nums 的长度,程序需要遍历数组一次;
空间复杂度:O(1)。额外使用的空间为有限个变量。