[LeetCode] - Longest Consecutive Sequence

来源:互联网 发布:控制手机使用时间软件 编辑:程序博客网 时间:2024/05/16 05:51

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.

这道题是个数据结构题,一定要看出来能用hashmap来解决。

把所有数据存进hashmap,然后遍历数组。如果当前数字在hashmap中,那么依次查找比它大和小的数字是否也在hashmap之中。总而言之,当明确了要用hashmap解决之后,这道题的思路就不是很难想了。具体见如下代码。

public class Solution {    public int longestConsecutive(int[] num) {        HashSet<Integer> set = new HashSet();        for(int x : num) {  // construct a hashset            set.add(x);        }                int max = 0;        for(int x : num) {            if(set.contains(x)) {                int temp=1, up=x+1, down=x-1;                set.remove(x);                while(set.contains(up)) {                    set.remove(up++);                    temp++;                }                while(set.contains(down)) {                    set.remove(down--);                    temp++;                }                if(temp>max) max=temp;            }        }        return max;     }}

0 0
原创粉丝点击