zoukankan      html  css  js  c++  java
  • [LeetCode] 128. Longest Consecutive Sequence Java

    题目:

    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.

    题意及分析:一个数组中连续的元素序列的长度。

    用一个set来查找,首先第一次遍历数组将数组添加到set中,去除重复元素,第二次对数组中的每个数查找其最长的连续串,然后将遍历过的数从set中移除。这样每个数都被遍历了两次,时间复杂度为o(n).

    代码:

    class Solution {
        public int longestConsecutive(int[] nums) {
            Set<Integer> set = new HashSet<>();
    
            for(int i=0;i<nums.length;i++){
                set.add(nums[i]);       //保持nums[i]中数的唯一性
            }
            int max = 0;
            for(int i=0;i<nums.length;i++){
                if(set.contains(nums[i])){
                    int count = 1;
                    set.remove(nums[i]);
    
                    int low = nums[i]-1;
                    while(set.contains(low)){
                        count++;
                        set.remove(low);
                        low--;
                    }
    
                    int high = nums[i]+1;
                    while(set.contains(high)){
                        count++;
                        set.remove(high);
                        high++;
                    }
                    max = Math.max(max,count);
                }
            }
            return max;
        }
    }
  • 相关阅读:
    第二期冲刺会议3
    第二期站立会议2
    意见汇总及改进方案
    第二期站立会议1
    第一期站立会议7
    第一期站立会议6
    第一期站立会议5
    第一期站立会议4
    第一期站立会议3
    第一期站立会议2
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7709761.html
Copyright © 2011-2022 走看看