let 128 Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

主题思想:因为是O(n) 复杂度,最开始想到建一个很大的数组,记录出现的数为1,然后查找最大连续为1的长度,但是由于数字可能很大,这种不可行。
但是这种思想大致如此,用HashMap记录一个数字和当前连续的长度,在插入一个数字之前,应该先检测是否能和左右两边联合起来。

很巧妙的思想: 求连续数组的思想:

AC 代码:

class Solution {
    public int longestConsecutive(int[] nums) {

       HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();

        int ans=0;
        for(int n: nums){

            if(!map.containsKey(n)){
                int left=map.getOrDefault(n-1,0);
                int right=map.getOrDefault(n+1,0);

                int sum=left+right+1;
                ans=Math.max(ans,sum);
                map.put(n,sum);
                map.put(n-left,sum);
                map.put(n+right,sum);

            }
        }
        return ans;
     }
}

猜你喜欢

转载自blog.csdn.net/the_conquer_zzy/article/details/79592184