[LeetCode]Longest Consecutive Sequence

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

 

posted @ 2015-12-01 10:02  Weizheng_Love_Coding  阅读(104)  评论(0编辑  收藏  举报