1. 程式人生 > >Longest Consecutive Sequence--記錄區間信息

Longest Consecutive Sequence--記錄區間信息

tput ash sorted max exit n+1 () complex ret

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.

Solution1: Sort it.

Solution2: Use hashmap to store consecutive intervals information, make sure the lowest and the highest both point to length of consecutive interval, such as [0,1,2,3,4], then (0->5, 4->5).

class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer,Integer> map = new
HashMap<Integer,Integer>(); int max = 0; for (int n : nums) { if (map.containsKey(n)) continue; map.put(n,1); int a = map.getOrDefault(n-1,0), b = map.getOrDefault(n+1,0); int newval = a+b+1; max = Math.max(max,newval);
if (a == 0 && b == 0) continue; //no neighbor map.put(n-a,newval); //update lowest map.put(n+b,newval); //update highest } return max; } }

Longest Consecutive Sequence--記錄區間信息