Longest Consecutive Sequence——LeetCode进阶路

原题链接https://leetcode.com/problems/longest-consecutive-sequence/

题目描述

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

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Accepted
192,857
Submissions
470,536

思路分析

利用set或者Hashmap都OK
!!!一定记得会有重复元素的情况出现,别问我怎么知道的……

源码附录

class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums == null || nums.length == 0)
        {
            return 0;
        }
        
        int result = 0;
        HashMap<Integer,Integer> map = new HashMap<>();
        
        for(int i:nums)
        {
            if(map.getOrDefault(i,0) == 0)//记得排除元素重复访问情况!……卡了好久
            {
                int low = map.getOrDefault(i-1,0);
                int high = map.getOrDefault(i+1,0);
                map.put(i,low+1+high);
                if(low >= 1)
                {
                    map.put(i-low,low+1+high);
                }
                if(high >= 1)
                {
                    map.put(high+i,low+1+high);
                }
                result = Math.max(result,low+1+high);
            }
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/Moliay/article/details/88428522