思路:首先对数组进行排序操作,当相邻的两个数差值为1时,说明连续,连续子序列长度+1。但是数组中存在重复数字,可以先用HashSet进行去重操作,但是空间复杂度较大。所以可以使用双指针算法,找出重复数字的最后一个索引。
import java.util.*;
public class Solution {
/**
* max increasing subsequence
* @param arr int整型一维数组 the array
* @return int整型
*/
public int MLS (int[] arr) {
// write code here
int n = arr.length;
if(n == 0 || n == 1) {
return n;
}
Arrays.sort(arr);
int res = 0, last = -1, cnt = 1;
for(int i = 0;i < n;i++) {
if(i + 1 < n && arr[i+1] == arr[i]) {
int j = i + 1;
while(j < n && arr[j] == arr[i]) {
j++;
}
i = j - 1;
}
if(last == -1) {
last = arr[i];
} else {
if(last + 1 == arr[i]) {
cnt++;
// res = Math.max(res,cnt);
} else {
cnt = 1;
}
last = arr[i];
}
res = Math.max(res,cnt);
}
return res;
}
}