zoukankan      html  css  js  c++  java
  • 最长连续序列

    给定一个未排序的整数数组,找出最长连续序列的长度。

    要求算法的时间复杂度为 O(n)。

    示例:

    输入: [100, 4, 200, 1, 3, 2]
    输出: 4
    解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

    package my;
    
    import java.util.Arrays;
    
    public class LongestConsecutiveXulie {
        //给定一个未排序的整数数组,找出最长连续序列的长度。
    
        public int longestConsecutive(int[] nums){
            if(nums.length== 0 ||nums == null){
                return 0;
            }
            Arrays.sort(nums);
            int max=1,cur=1;
            for(int i=1; i<nums.length; i++){
                if(nums[i] != nums[i-1]){
                    if(nums[i-1] + 1 == nums[i]){
                        cur++;
                    }else{
                        max = Math.max(max,cur);
                        cur=1;
                    }
                }
            }
            return Math.max(max,cur);
        }
    
        public static void main(String [] args){
            int [] nums = {100, 4, 200, 1, 3, 2};
            LongestConsecutiveXulie lcx= new LongestConsecutiveXulie();
            int  n = lcx.longestConsecutive(nums);
            System.out.println(n);
        }
    }
  • 相关阅读:
    BeautifulSoup
    requests
    安装xpath helper
    取消搜狗输入法的快捷键
    numpy初识 old
    Jupyter Notebook 快捷键
    安装numpy、matplotlib
    JavaScript 继承 -JavaScript高级程序设计
    mac /windows
    unicode 地址
  • 原文地址:https://www.cnblogs.com/goodtest2018/p/13562830.html
Copyright © 2011-2022 走看看