题目

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:

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

Example 2:

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

Constraints:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

题意

给定一个数组,从中选择若干数字组成序列,使该序列中的数字依次递增加一,求满足的最长的序列。

思路

O(N)方法:先将所有数存入HashSet中,利用HashSet找到每一个满足序列的第一个数字(即找到数字num,使得num在set中,但num-1不在set中),从该数字出发求出整个序列的长度。实际上每个数字被访问了两次,复杂度为O(N)。


代码实现

Java

  1. class Solution {
  2. public int longestConsecutive(int[] nums) {
  3. int ans = 0;
  4. Set<Integer> set = new HashSet<>();
  5. for (int num : nums) {
  6. set.add(num);
  7. }
  8. for (int num : set) {
  9. if (set.contains(num - 1)) continue;
  10. int cnt = 1;
  11. while (set.contains(num + 1)) {
  12. cnt++;
  13. num++;
  14. }
  15. ans = Math.max(ans, cnt);
  16. }
  17. return ans;
  18. }
  19. }