美文网首页
128. Longest Consecutive Sequenc

128. Longest Consecutive Sequenc

作者: greatseniorsde | 来源:发表于2018-02-05 02:45 被阅读0次

    竟然是hard, 解法是比较巧妙但很好理解,没有复杂算法

    class Solution {
        public int longestConsecutive(int[] nums) {
            if (nums == null || nums.length == 0){
                return 0;
            }
            Set<Integer> set = new HashSet<>();
            for (int num : nums){
                set.add(num);
            }
            //[100,4,200,1,3,2]
            //longest = 0
            //num : 100
            //down = 99
            //up = 101
            int longest = 0;
            for (int i = 0; i < nums.length; i++){
                int down = nums[i] - 1;
                while (set.contains(down)){
                    set.remove(down);
                    down--;
                }
                int up = nums[i] + 1;
                while (set.contains(up)){
                    set.remove(up);
                    up++;
                }
                //actually up - 1 - (down + 1) + 1
                longest = Math.max(longest, up - down - 1);
            }
            return longest;
        }
    }
    

    相关文章

      网友评论

          本文标题:128. Longest Consecutive Sequenc

          本文链接:https://www.haomeiwen.com/subject/vgtbzxtx.html