最长连续序列-leecode
程序员文章站
2024-02-25 10:07:52
...
动态规划解法:
public static int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int n = nums.length;
int min = Integer.MAX_VALUE;
int minIndex = 0;
for (int i = 0; i < n; i++) {
if (nums[i] < min) {
min = nums[i];
minIndex = i;
}
}
int[] C = new int[n];
C[minIndex] = 1;
Integer[] numsInteger = Arrays.stream(nums).boxed().toArray(Integer[]::new);
for (int i = n - 1; i >= 0; i--) {
if (nums[i] == min) {
continue;
}
int preIndex = new ArrayList<>(Arrays.asList(numsInteger)).indexOf(nums[i] - 1);
if (preIndex != -1) {
C[i] = C[preIndex] + 1;
} else {
C[i] = 1;
}
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (C[i] > max) {
max = C[i];
}
}
return max;
}
未完待优化。
上一篇: Python学习之路(2)
下一篇: 算法_无重复字符的最长子串(js)