哈希表

  1. public int longestConsecutive(int[] nums) {
  2. Set<Integer> set = new HashSet<>();
  3. for (int num : nums) {
  4. set.add(num);
  5. }
  6. int maxLen = 0;
  7. for (int n : set) {
  8. // 以当前数开头的序列
  9. if (!set.contains(n - 1)) {
  10. int currentlen = 1;
  11. while (set.contains(n + 1)) {
  12. n += 1;
  13. currentlen++;
  14. }
  15. maxLen = Math.max(maxLen, currentlen);
  16. }
  17. // 若set中包含你前面一个数,说明轮到不你来开头
  18. }
  19. return maxLen;
  20. }