LeetCode_哈希表_中等_128. 最长连续序列

x33g5p2x  于2022-05-18 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(179)

1.题目

给定一个未排序的整数数组 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

提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-consecutive-sequence

2.思路

注:字节二面原题

(1)排序(但不符合题目要求)
(2)哈希表
思路参考本题官方题解

3.代码实现(Java)

//思路1————排序(但不符合题目要求)
public int longestConsecutive(int[] nums) {
	//对数组元素进行升序排序
    Arrays.sort(nums);
    int length = nums.length;
    if (length <= 1)  {
        return length;
    }
    int maxLength = 1;
    for (int i = 1; i < length; i++) {
        int tmpLength = 1;
        //遍历每个数字连续的序列,用 res 记录最长的结果
        while (i < length) {
            if (nums[i] == nums[i - 1] + 1) {
                tmpLength++;
                i++;
            } else if (nums[i] == nums[i - 1]) {
            	//跳过排序后相同元素相邻的情况
                i++;
            } else {
                break;
            }          
        }
        maxLength = Math.max(maxLength, tmpLength);
    }
    return maxLength;
}
//思路2————哈希表
public int longestConsecutive(int[] nums) {
    //将数组中的元素存放到 hashSet 中,以去除重复元素
    Set<Integer> hashSet = new HashSet<>();
    for (int num : nums) {
        hashSet.add(num);
    }
    int maxLength = 0;
    for (int num : hashSet) {
        if (!hashSet.contains(num - 1)) {
            int curNum = num;
            int tmpLength = 1;
            while (hashSet.contains(curNum + 1)) {
                curNum++;
                tmpLength++;
            }
            maxLength = Math.max(maxLength, tmpLength);
        }
    }
    return maxLength;
}

相关文章

微信公众号

最新文章

更多