Longest Consecutive Sequence

来源:互联网 发布:java excel报表工具 编辑:程序博客网 时间:2024/05/16 13:59

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.

 

Solution


1. Use a hash set to store the element.

2. Iterate the array to get the length of the longest consecutive elements sequence.


public class Solution {    public int longestConsecutive(int[] nums) {        if (nums == null || nums.length == 0)            return 0;                    HashSet<Integer> set = new HashSet<Integer>();                for (int i = 0; i < nums.length; i++) {            set.add(nums[i]);        }        int max = 1;                for (int i = 0; i < nums.length; i++) {            int left = nums[i] - 1;            int right = nums[i] + 1;            int count = 1;                        while (set.contains(left)) {                count++;                set.remove(left);                left--;            }                        while (set.contains(right)) {                count++;                set.remove(right);                right++;            }                        max = Math.max(count, max);        }                return max;    }}


0 0
原创粉丝点击