文章目录
17, 128. 最长连续序列
思路1: 暴力解法(通过hashmp确认是否包含)
思路2: 思路1有优化,前驱节点不存在,才需要计算连续长度
package com.shangguigu.dachang.algrithm.A06_hashTable;
import java.util.HashMap;
import java.util.HashSet;
/**
* @author : 不二
* @date : 2022/4/13-下午9:42
* @desc : 128. 最长连续序列
* https://leetcode-cn.com/problems/longest-consecutive-sequence/
*
**/
public class A59_longestConsecutive {
public static void main(String[] args) {
// int[] nums = {100, 4, 200, 1, 3, 2};
// int[] nums = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};
int[] nums = {0, -1};
int i = longestConsecutive(nums);
System.out.println("结果是:" + i);
}
/**
* 思路2:思路1优化,只有当前驱节点不存在当时候,才需要遍历
* 比如 数据中存在2,也存在3,那么3就不需要处理了,到时候处理2的时候自然比3的要长。
*
* 时间复杂度:O(n)
*/
public static int longestConsecutive_v2(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
int result = 0;
for (int i = 0; i < nums.length; i++) {
int j = nums[i];
// 前驱节点不存在,才有必要去计算最长序列,要不然,计算前驱节点的就可以了
if (!set.contains(nums[i]-1)) {
int count = 0;
while (set.contains(j)) {
count++;
j++;
}
result = Math.max(result, count);
}
}
return result;
}
/**
* 思路1:暴力解法
*/
public static int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
int result = 0;
for (int i = 0; i < nums.length; i++) {
int j = nums[i];
int count = 0;
while (set.contains(j)) {
count++;
j++;
}
result = Math.max(result, count);
}
return result;
}
}