leetcode128

这道题主要思路就是hash表+递归,hash表中放的是以数组中每个数结尾时最长连续子序列的长度,所以一开始都是1,因为还不知道它前面有什么数。

然后遍历每个放入hash表中的key(记为num),用递归找比它小1的数num-1是否存在在hash表中,它的以num-1结尾的最长连续子序列的长度是多少,然后从num-1继续向前找,直到找到num所在连续子序列的第一个元素。假设从num开始递归,最后以num以及之前的存在在子序列中的数结尾时的子序列长度都能算出来。

为了避免重复计算,发现一个key它的value不为1时,就说明以该key结尾的连续子序列长度已经算出来了,所以直接return 就好。
最后hashset中存放的就是实际中以每个数结尾时的连续子序列长度,他们中的最大值就是题目所求。

class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<>();
        int res= 0;
        for(int num:nums){
            map.put(num,1);
        }
        for(int num:map.keySet()){
            back(map,num);
        }
        for(int num:map.keySet()){
            res = Math.max(res,map.get(num));
        }
        return res;
    }
    private void back(HashMap<Integer,Integer> map,int num){
        if(map.get(num)!=1) return;
        if(map.containsKey(num-1)){
            back(map,num-1);
            map.put(num,map.get(num-1)+1);
        }
    }
}
原文地址:https://www.cnblogs.com/ljf-0/p/14183040.html