算法-leetcode-链表问题- 128. 最长连续序列
文章目录
17, 128. 最长连续序列
思路1: 暴力解法(通过hashmp确认是否包含)
思路2: 思路1有优化,前驱节点不存在,才需要计算连续长度
package com.shangguigu.dachang.algrithm.A06_hashTable;
import java.util.HashMap;
import java.util.HashSet;
public class A59_longestConsecutive {
public static void main(String[] args) {
int[] nums = {0, -1};
int i = longestConsecutive(nums);
System.out.println("结果是:" + i);
}
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;
}
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;
}
}