题目描述:
    image.png
    image.png
    解析:hashSet作记录 从左往右搜 从右往左搜

    1. class Solution {
    2. public int longestConsecutive(int[] nums) {
    3. HashSet<Integer> set = new HashSet<>();
    4. int longest = 0; //记录长度
    5. for (int num : nums) {
    6. set.add(num);
    7. }
    8. for (int num : nums) {
    9. //从左往右搜 例如100,搜索101,102,103....
    10. int currNum = num;
    11. int currLong = 1;
    12. while (set.remove(currNum + 1)) currNum++;
    13. currLong += currNum - num;
    14. //从右往左搜 例如100,搜索99,98,97....
    15. currNum = num;
    16. while (set.remove(currNum - 1)) currNum--;
    17. currLong += num - currNum;
    18. longest = Math.max(longest, currLong);
    19. }
    20. return longest;
    21. }
    22. }