128.最长连续序列

class Solution {
    /**
     * 计算给定数组中的最长连续序列长度
     * 存在逻辑缺陷的初始实现(需结合注释理解问题)
     * @param nums 未排序的整数数组(可能包含重复元素)
     * @return 最长连续序列的长度
     */
    public int longestConsecutive(int[] nums) {
        // 边界条件:空数组直接返回0
        if (nums.length == 0) return 0;
        
        Arrays.sort(nums); // 通过排序使连续元素相邻
        int temp = 1;      // 当前连续序列长度计数器
        int ans = 1;       // 记录最长连续序列长度

        // 遍历排序后的数组,比较相邻元素
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i + 1] - nums[i] == 1) {
                temp++;    // 连续时递增计数器
            } else if (nums[i + 1] != nums[i]) {  
                // 非连续且非重复元素时重置计数器
                // 当前实现缺少此判断,导致重复元素会错误重置计数器
                ans = Math.max(temp, ans);
                temp = 1; // 应添加此重置操作
            }
            // 此处无论是否连续都更新结果,可能导致过早覆盖最大值
            ans = Math.max(temp, ans);
        }
        // 缺少最终比较:循环结束后需再次更新最大值
        // ans = Math.max(temp, ans); // 应添加此行确保准确性
        return ans;
    }
}

posted @ 2025-05-20 19:13  星星永远发着光  阅读(9)  评论(0)    收藏  举报