【问题描述】
给定一个整数数组,返回它其中最长的连续整数数列长度。
例如 a[] = {100,4,200,1,3,2} 因为其中包含1,2,3,4所以返回4.
【C/C++代码】
int longest(const int num[], int n) {
unordered_map<int, int> hash;
for (int i=0; i<n; ++i)
hash[num] = 1;
int ans=0;
for (int i=0; i<n; ++i) {
unordered_map<int, int>::iterator it = hash.find(num+1);;
for (int j=num+1; it!=hash.end(); it=hash.find(++j)) {
hash[num] += it->second;
hash.erase(it);
}
ans = max(ans, hash[num]);
}
return ans;
}
另附上另一位博友使用并查集解决的方法,据说时间复杂度O(n)
#define N 200001
#define ADD N/2
#define maxn 1000
struct {
int root;
int count;
}*set, ARRAY[N] = {{0, 0}};
int arr[maxn];
int length;
int max (int a, int b) {
return a > b ? a : b;
}
void init () {
set = ARRAY + 1 + N / 2;
}
void update (int n) {
if ((!set[n].root) && (!set[n].count)) {
set[n].root = n;
set[n].count = 1;
}
}
int find (int n) {
if (!set[n].count) {
return n;
}
if (n == set[n].root) {
return n;
}
return set[n].root = find(set[n].root);
}
int connect (int n, int left, int right) {
if (set[left].count && set[right].count) {
set[right].root = left;
set[left].count += set[right].count + 1;
set[n].root = left;
return set[left].count;
}
if (set[left].count) {
set[left].count++;
set[n].root = left;
return set[left].count;
}
if (set[right].count) {
set[right].count++;
set[n].root = right;
return set[right].count;
}
return 1;
}
int LongestSubArrary (int* arr, int length) {
int res = 0;
int i;
for (i = 0; i < length; ++i) {
update(arr);
res = max(res, connect (arr, find(arr - 1), find(arr + 1)));
}
return res;
}
int main () {
int t, i;
init();
scanf("%d", &t);
while (t--) {
memset(ARRAY, 0, sizeof(ARRAY));
scanf("%d", &length);
for (i = 0; i < length; ++i) {
scanf("%d", &arr);
}
printf ("%d\n", LongestSubArrary(arr, length));
}
return 0;
}
本文介绍了一种通过哈希表和迭代查找相邻元素的方法来确定整数数组中连续整数序列的最大长度。同时,提供了一个使用并查集的替代解决方案,该方法的时间复杂度为O(n)。

2286

被折叠的 条评论
为什么被折叠?



