- 最长连续序列
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
测试用例:
[0]
[0,-1]
[1,2,0,1]
[2147483646,-2147483647,0,2,2147483644,-2147483645,2147483645]
[100,4,200,1,3,2]
思路:先排序,然后一次遍历
int myCompare(const void *num1, const void *num2) {
int a = *(int *)num1;
int b = *(int *)num2;
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
//直接return a-b;有可能出现int存储溢出的问题
return a - b;
}
void printNums(int * nums, int numsSize) {
for (int i=0; i<numsSize; i++) {
printf("%d\t", nums[i]);
}
printf("\n");
}
int longestConsecutive(int* nums, int numsSize){
if (numsSize < 2) {
return numsSize;
}
//printNums(nums, numsSize);
qsort(nums, numsSize, sizeof(int), myCompare);
//printNums(nums, numsSize);
int left = 0, right = 0, maxLen = 0;
for (int i=0; i<numsSize-1; i++) {
if (nums[i+1] == nums[i]) {
left++;
} else if (nums[i+1] > nums[i] + 1) {
int tmp = right - left + 1;
maxLen = tmp > maxLen ? tmp : maxLen;
left = i + 1;
}
right = i + 1;
}
int tmp = right - left + 1;
maxLen = tmp > maxLen ? tmp : maxLen;
return maxLen;
}
/*4ms,6.1MB*/
思路二:
int myCompare(const void *num1, const void *num2) {
//将int存储空间直接扩展为long long,注意这时候输出的排序顺序有可能正整数在前,负整数在后
//如:2 2147483644 2147483645 2147483646 -2147483647 -2147483645 0
return (long long) *(int *) num1 - (long long) *(int *) num2;
}
void printNums(int * nums, int numsSize) {
for (int i=0; i<numsSize; i++) {
printf("%d\t", nums[i]);
}
printf("\n");
}
int longestConsecutive(int* nums, int numsSize){
if (numsSize < 2) {
return numsSize;
}
//printNums(nums, numsSize);
qsort(nums, numsSize, sizeof(int), myCompare);
//printNums(nums, numsSize);
int left = 0, right = 0, maxLen = 0;
for (int i=0; i<numsSize-1; i++) {
if (nums[i+1] == nums[i]) {
left++;
} //else if (nums[i+1] > nums[i] + 1) {
else if ((long long)nums[i+1] - (long long)nums[i] != 1LL) {
int tmp = right - left + 1;
maxLen = tmp > maxLen ? tmp : maxLen;
left = i + 1;
}
right = i + 1;
}
int tmp = right - left + 1;
maxLen = tmp > maxLen ? tmp : maxLen;
return maxLen;
}
/*8ms,5.9MB*/
时间复杂度:O(nlogn)——未能满足题目中要求的O(n),可以使用hash表优化,后续补充。
空间复杂度:O(1)