題目:
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:數組未排序
3:可能存在重複數字
思路
1:先排序,然後根據排序結果依次遍歷搜索連續序列
2:因爲存在重複,想到set集合。首先將數組去全部放入set集合中。然後遍歷刪除左右數字。
3:新建一個map集合,key是當前數字的值,value是已經在map集合中該數字的連續序列長度。依次將數組放入map集合中,在放入過程中,如果是連續序列,只要找到小1和大1的map的值,然後進行相加+1即可。在過程中,除了要更新當前的值,還需要更新左右結點的值。
實現代碼
//思路1
class Solution {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
if(nums.length == 1)
return 1;
//對數組進行排序再去找最長序列
Arrays.sort(nums);
int res = 0, tmp = 1;
for(int i = 0; i < nums.length-1; i++){
//可能存在重複
if((nums[i] == nums[i + 1]) || (nums[i] == nums[i + 1] - 1)){
//如果不重複,就加1,重複略過
if(nums[i] == nums[i + 1] - 1)
tmp += 1;
}
else {
res = Math.max(res , tmp);
tmp = 1;
}
}
//不能直接返回res,遇到[1,2,3,4,5]這種可能之前沒有進入else語句
return Math.max(res , tmp);
}
}
//思路2
class Solution {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
if(nums.length == 1)
return 1;
//加入set集合,去重
Set<Integer> set = new HashSet<>();
for(int n : nums)
set.add(n);
int res = 0;
for(int n: nums){
int count = 0;
//如果set已經空,則返回;
if(set.isEmpty())
break;
//對於數組中的數,刪除左邊的數
int val = n;
while(set.remove(val--))
count ++;
//刪除右邊的數,(n已在上式中刪除)
val = n + 1;
while(set.remove(val++))
count ++;
//判斷完每個連續的數塊,就更新一次最大值
res = Math.max(count,res);
}
return res;
}
}
//思路3
class Solution {
public int longestConsecutive(int[] nums) {
int res = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int n : nums){
if(!map.containsKey(n)){
int left = (map.containsKey(n - 1)) ? map.get(n - 1) : 0;
int right = (map.containsKey(n + 1)) ? map.get(n + 1) : 0;
// sum: length of the sequence n is in
int sum = left + right + 1;
map.put(n, sum);
// keep track of the max length
res = Math.max(res, sum);
// extend the length to the boundary(s)
// of the sequence
// will do nothing if n has no neighbors
map.put(n - left, sum);
map.put(n + right, sum);
}
else {
// duplicates
continue;
}
}
return res;
}
}