文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. 问题描述
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
2. 求解
题中明确要求时间复杂度为O(n),因此这道题肯定不能使用循环遍历。这道题主要是考察哈希表,因为哈希表每次查询的时间复杂度为O(1)。因此首先要将数组转为Map。然后分别查询每个数字的前一个数与后一个数,统计数字连续的数量。如果在哈希表中存在相邻的数,查询后应该从哈希表中删除,当然不删也可以。如果哈希表为空,则直接跳出循环,不再遍历。
public class Solution {
public int longestConsecutive(int[] nums) {
int max = 0;
int count = 0;
Map<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0; i < nums.length; i++) {
map.put(String.valueOf(nums[i]), nums[i]);
}
for(int i = 0; i < nums.length; i++) {
count = 1;
int x = nums[i];
while(true) {
int temp = --x;
if(map.containsKey(String.valueOf(temp))) {
map.remove(String.valueOf(temp));
count++;
}else {
break;
}
}
//必须重置x
x = nums[i];
while(true) {
int temp = ++x;
if(map.containsKey(String.valueOf(temp))) {
map.remove(String.valueOf(temp));
count++;
}else {
break;
}
}
if(count > max) {
max = count;
}
if(map.isEmpty()) {
break;
}
}
return max;
}
}