Longest Consecutive Sequence

Longest Consecutive Sequence

问题:

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

思路:

  HashSet进行存储

我的代码:

public class Solution {

    public int longestConsecutive(int[] num) {

        if(num == null || num.length == 0)  return 0;

        Set<Integer> set = new HashSet<Integer>();

        for(int i = 0; i < num.length; i++)

        {

            set.add(num[i]);

        }

        int maxLen = 0;

        for(int i = 0; i < num.length; i++)

        {

            if(set.contains(num[i]))

            {

                int tmp = num[i] - 1;

                int len = 1;

                set.remove(num[i]);

                while(set.contains(tmp))

                {

                    set.remove(tmp);

                    len++;

                    tmp--;

                }

                tmp = num[i] + 1;

                while(set.contains(tmp))

                {

                    set.remove(tmp);

                    len++;

                    tmp++;

                }

                maxLen = Math.max(maxLen,len);

            }

        }

        return maxLen;

    }

}
View Code

学习之处:

  数组映射成,用HashSet进行存储可以在O(1)快速的查找任何一个数值

你可能感兴趣的:(sequence)