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;
        }
    }
  • 相关阅读:
    Chapter 4: Using Custom Property Types
    Chapter 2: Connecting to C++ Methods and Signals
    C++ Extensions: Reference examples
    qt exec
    qt component desktop
    Qt事件处理机制
    Tutorial: Writing QML Extensions with C++
    label for
    (一) HTTP 1.1支持的状态代码
    一些常用的特殊字符
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7709761.html
Copyright © 2011-2022 走看看