Longest contiguous sequence
Title description: Given an unsorted integer array nums, find the length of the longest continuous sequence of numbers (the sequence elements are not required to be continuous in the original array).
Please design and implement an O(n) algorithm to solve this problem.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/longest-consecutive-sequence/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: hash table
Because the hash lookup is relatively fast, a hash table is used to assist the calculation. The specific processing process is as follows:
- First, use HashSet to de-duplicate the numbers in the original array to get numsSet;
- Then, traverse all the numbers in the numsSet, use currentConsecutiveNums to record the current number as the starting point, the continuous number and the longest sequence length in the numsSet, find these continuous numbers in the numsSet through a hash search, and finally get the current number corresponding The longest continuous sequence length;
- If the length of the longest continuous sequence corresponding to the current number is greater than the known longest continuous sequence longestConsecutiveNums, the value of the longest continuous sequence longestConsecutiveNums is updated.
Finally, return longestConsecutiveNums which is the length of the longest continuous sequence.
import java.util.HashSet;
import java.util.Set;
public class LeetCode_128 {
/**
* 哈希表
*
* @param nums
* @return
*/
public static int longestConsecutive(int[] nums) {
// 去重后的数
Set<Integer> numsSet = new HashSet<>();
for (int num : nums) {
numsSet.add(num);
}
// 记录最长的连续序列
int longestConsecutiveNums = 0;
for (Integer num : numsSet) {
if (!numsSet.contains(num - 1)) {
// 当前的数
int currentNum = num;
// 当前的数连续的序列的长度,初始值为1
int currentConsecutiveNums = 1;
// 获取以当前数字为起点,连续的数且在numsSet中的长度
while (numsSet.contains(currentNum + 1)) {
currentNum += 1;
currentConsecutiveNums += 1;
}
// 如果当前的最大连续长度大于最大的的连续序列,则更新最大的连续序列
longestConsecutiveNums = Math.max(longestConsecutiveNums, currentConsecutiveNums);
}
}
return longestConsecutiveNums;
}
public static void main(String[] args) {
int[] nums = new int[]{100, 4, 200, 1, 3, 2};
// 测试用例,期望输出: 4
System.out.println(longestConsecutive(nums));
}
}
[Daily Message] first youth is given by God; the second youth is based on our own efforts.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。