题目:
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.
本题是想要寻找一个数组中最长的连续序列。有几个点需要注意的是:1,数组未排序;2,可能存在重复数字。我看到题目第一个想到的是先将数组进行排序,这样我们可以方便的找到连续的数字。思路很简单,代码入下:
public int longestConsecutive(int[] nums) {
if(nums.length == 0 || nums == null)
return 0;
if(nums.length == 1)
return 1;
Arrays.sort(nums);
int max = 0, tmp = 1;
for(int i=0; i<nums.length-1; i++){
if (nums[i] == nums[i+1] - 1 || nums[i] == nums[i+1]){
if (nums[i] == nums[i+1] - 1)
tmp ++;
}else{
max = Math.max(max, tmp);
tmp = 1;
}
}
return Math.max(max, tmp);
}
这种方法击败了96%的用户,很惊呀,然后去看了下discuss,发现原来别人都是用hashSet或者HashMap去做,然后找了一个效率相对比较高的程序,可以击败86%的用户。代码入下:
public int longestConsecutive1(int[] nums) {
Set<Integer> set = new HashSet<>();
//先将数组中的每个数添加到set中,实现去重;
for(int n: nums) set.add(n);
int max = 0;
//接下来遍历数组
for(int n: nums){
int count = 0;
//如果set已经空,则返回;
if(set.isEmpty()) break;
//对于数组中的数,将其左右相连的数都remove掉,这样set会越来越小
int val = n;
while(set.remove(val--))
count ++;
val = n;
while(set.remove(++val))
count ++;
//判断完每个连续的数块,就更新一次最大值
max = Math.max(count,max);
}
return max;
}