128. 最长连续序列

93 阅读1分钟

image.png

public int longestConsecutive(int[] nums) {
      int ans = 0;
      Set<Integer> set = new HashSet<>();
      for (int i = 0; i < nums.length; i ++ ) {
          set.add(nums[i]);
      }

      for (int num : nums) {
          int cur = num;
          int max = 0;
          // set中 包含 num-1 则不为左边界 
          if (set.contains(num - 1)) {
              continue;
          } else {
              while (set.contains(cur)) {
                  max ++;
                  cur ++;
              }
          }
          ans = Math.max(max, ans);
      }
      return ans;
  }

解析

题目要求最长连续的的序列,只需要将所有的数遍历放在一个set集合内去找最长额连续子序列。
tips:
如已经遍历一个子序列[1,2,3,4,5],此时我们不需要继续便利子序列[2,3,4,5], 因此我们
只需要找到最左边的边界值进行遍历,判断当前的数字bnum是否为边界,如果num-1已经在
set中时,说明该数字不是边界不再遍历,节省时间。