[LeetCode] 无序数组中的最长连续数列 The Longest Consecutive Sequence in an unsorted array
给你一个无序的数组,{5, 7, 3, 4, 9, 10, 1, 15, 1, 3, 12, 2, 11},那么最长的连续数列是{1, 2, 3, 4, 5}。
思路:
Dump everything to a hash set.
Now go through the hashset. For each element, look up the set for all values neighboring the current value. Keep track of the largest sequence you can find, while removing the elements found from the set. Save the count for comparison.
Repeat this until the hashset is empty.
Assuming lookup, insertion and deletion are O(1) time, this algorithm would be O(N) time.
伪代码如下:
int start, end, max
int temp_start, temp_end, count
hashset numbers
for element in array:
numbers.add(element)
while !numbers.empty():
number = numbers[0]
count = 1
temp_start, temp_end = number
while numbers.contains(number - 1):
temp_start = number - 1; count++
numbers.remove(number - 1)
while numbers.contains(number + 1):
temp_end = number + 1; count++
numbers.remove(number + 1)
if max < count:
max = count
start = temp_start; end = temp_end
max_range = range(start, end)
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include <set>
#include <string.h>
using namespace std;
int LCS(int arr[], int n)
{
set<int> arr_set (arr, arr+n);
int maxCount = 0, // length of the longest consecutive subsequence
left_range = 0, // start of LCS
right_range = 0; // end of LCS
while(!arr_set.empty()){
// each time, retrieve the first element in the set
set<int>::iterator iter = arr_set.begin();
int val = *iter-1;
int left = *iter, right = *iter;
int count = 1;
// find out the neighboring numbers less than *iter
while(arr_set.find(val)!=arr_set.end())
{
count++;
left--;
arr_set.erase(val);
val--;
}
// find out the neighboring numbers greater than *iter
val = *iter+1;
while(arr_set.find(val)!=arr_set.end())
{
count++;
right++;
arr_set.erase(val);
val++;
}
// update if necessary
if(count>maxCount)
{
maxCount = count;
left_range = left;
right_range = right;
}
arr_set.erase(*iter);
}
cout<<left_range<<"|"<<right_range<<endl;
return maxCount;
}
int main()
{
int arr[] = {5, 7, 3, 4, 9, 10, 1, 15, 1, 3, 12, 2, 11};
int a = LCS(arr, sizeof(arr)/sizeof(int));
cout<<a;
}