lc-128


/**
Given an unsorted array of integers nums, return the length of the longest 
consecutive elements sequence. 

 You must write an algorithm that runs in O(n) time. 

 
 Example 1: 

 
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. 
Therefore its length is 4.
 

 Example 2: 

 
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
 

 
 Constraints: 

 
 0 <= nums.length <= 10⁵ 
 -10⁹ <= nums[i] <= 10⁹ 
 
 Related Topics并查集 | 数组 | 哈希表 

 👍 1382, 👎 0 

*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> hashSet = new HashSet<>();

        for (int num : nums) {
            hashSet.add(num);
        }

        int result = 0;

        for (int value : hashSet) {
            if (!hashSet.contains(value - 1)) {
                int len = 1;
                int i = value + 1;
                while (hashSet.contains(i)) {
                    len++;
                    i++;
                }

                if (len > result) {
                    result = len;
                }
            }
        }

        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !