LeetCode每日一题:数组最长连续元素的个数

问题描述

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.
Your algorithm should run in O(n) complexity.

问题分析

这个问题让我们求一个数组中最长的连续元素组的个数,但是规定在O(n)时间内要完成,所以我们不能用排序
由于本题只要我们求元素的个数,这题我们可以用HashSet来解决,每次查找了一个数num后,查找num+1和num-1是否在数组里,

  • 在的话count+1,再查找num+1+1或num-1-1在不在数组里,
  • 不在的话结束查找这个数,查找num[i+1]

代码实现

public int longestConsecutive(int[] num) {
        int n = num.length;
        int result = 1;
        HashSet set = new HashSet<>();
        for (int i = 0; i < n; i++) {
            set.add(num[i]);
        }
        for (int i = 0; i < n; i++) {
            int pre = num[i] - 1;
            int next = num[i] + 1;
            int count = 1;
            while (set.remove(pre)) {
                pre--;
                count++;
            }
            while (set.remove(next)) {
                next++;
                count++;
            }
            if (count > result) result = count;
        }
        return result;
    }

你可能感兴趣的:(LeetCode每日一题:数组最长连续元素的个数)