Leetcode热题100--新手出发3--128.最长连续序列
题目
128.最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1:
* 输入:nums = [100,4,200,1,3,2]
* 输出:4
* 解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
* 输入:nums = [0,3,7,2,5,8,4,6,0,1]
* 输出:9
具体实现
暴力求解
思路及算法:
思路:先将数组进行排序,然后逐一判断是否是连续的
实现:
1、将数组进行排序,将数组第一个值和结果个数记录一下
2、遍历该排序好的数组:
1) 当记录的当前值和遍历的值相同,则跳过该此循环
2) 当记录的当前值+1和遍历的值相同,则更新当前值和结果个数
3) 当不符合上述两种条件时,说明已经无法连续,则需要重新构建新的初始值和结果值
4) 最后判断当前的结果和存储的结果进行对比,取得最大的一段值返回
可能会忽略的细节:
1、会出现多个相同值的情况,这不属于连续数字段,要额外筛选和判断
2、可能会有多段连续值,需要做最长段判断
int[] nums128 = new int[] { 100, 4, 200, 1, 3, 2 };
int[] nums128_2 = new int[] { 0, 3, 7, 2, 5, 8, 4, 6, 0, 1 };
int[] nums128_3 = new int[] { 9, 1, 4, 7, 3, -1, 0, 5, 8, -1, 6 };// -1 -1 0 1 3 4 5 6 7 8 9
public int LongestConsecutive(int[] nums)
{
if (nums.Length == 0) return 0;
Array.Sort(nums);
int finalResult = 1;
int result = 1;
int temp = nums[0];
for (int i = 1; i < nums.Length; i++)
{
if(temp == nums[i]) continue;
else if (temp + 1 == nums[i])
{
result++;
temp = nums[i];
}
else
{
if(finalResult < result) finalResult = result;
temp = nums[i];
result = 1;
}
}
if (finalResult < result) finalResult = result;
return finalResult;
}
哈希表求解
思路及算法:
思路:枚举数组中的每个数 x,考虑以其为起点,不断尝试匹配 x+1,x+2,⋯ 是否存在,假设最长匹配到了 x+y,那么以 x 为起点的最长连续序列即为 x,x+1,x+2,⋯,x+y,其长度为 y+1,我们不断枚举并更新答案即可。
分析:for循环的过程是在筛选当前值是否是某个连续数字段的起始部分,不是则继续循环;若是起始部分,则按照该值顺序一直遍历是否存在当前值+1,若存在则一直累加,若不存在,则结束累加,并和之前存入的长度值进行对比,取得最大值。因为其中过滤了while的循环条件,因此总时间复杂度是O(n)。
实现:
1、先将所有值存入到字典中
2、再次遍历数组,若字典中不存在当前值-1的值(递减),并记录当前状态
3、while循环判断是否存在当前值+1的值(递增)的情况,最后找出最长段
public int LongestConsecutive2(int[] nums)
{
int longestStreak = 0;
Dictionary<int, int> dictLong = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
if (!dictLong.ContainsKey(nums[i])) dictLong.Add(nums[i], longestStreak);
}
for (int i = 0; i < nums.Length; i++)
{
if (!dictLong.ContainsKey(nums[i] - 1))
{
int currentNum = i;
int currentSteak = 1;
while (dictLong.ContainsKey(currentNum + 1))
{
currentNum += 1;
currentSteak += 1;
}
longestStreak = Math.Max(longestStreak, currentNum);
}
}
return longestStreak;
}