leetcode——128. 最长连续序列

用哈希表

public int longestConsecutive(int[] nums) {  //未排序的数组,先进行排序再进行遍历???光排序就是O(n2)的时间复杂度了吧。
        //还有啥办法
        //加入哈希map,比较有没有与当前数字连续的键,如果有就进行添加,按顺序。但是这样的话,并不能一下子查出连续的值
        //用哈希map,添加进去,然后在访问提取的时候就比较方便了吧。
        if(nums.length == 0){
            return 0;
        }
        HashMap<Integer,Boolean> used = new HashMap<Integer, Boolean>();
        for(int i : nums) {
            used.put(i,false);
        }
        int longest = 1;
        for(int i : nums){
            if(used.get(i)){
                continue;
            }
            int length = 1;
            used.put(i,true);
            for(int j = i+1; used.containsKey(j) ;j++){
                used.put(j,true);
                length++;
            }
            for(int j = i-1;used.containsKey(j);j--){
                used.put(j,true);
                length++;
            }
            longest = Math.max(longest,length);
        }
        return longest;
    }

——2020.7.9

我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/13272513.html