zoukankan      html  css  js  c++  java
  • 找出最长序列的长度

    /****
     * 给定一个未排序的整数数组,找出最长连续序列的长度。
     *
     * 要求算法的时间复杂度为 O(n)。
     *
     * 示例:
     *
     * 输入: [100, 4, 200, 1, 3, 2]
     * 输出: 4
     * 解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
     */
    import java.util.Arrays;
    
    public class LongestConsecutiveSolution {
        public static 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 = new int[] {100, 4, 200, 1, 3, 2,5,9,11,12,13,14,15,16,17};
            int  outPut=longestConsecutive(nums);
            System.out.println(outPut);
        }
    }
  • 相关阅读:
    交互式监控工具glances
    性能测试工具Locust
    CentOS 7 安装 PostgreSQL 教程
    Vue表单
    Vue事件处理
    Vue列表渲染
    Vue条件渲染
    Vue中class与style绑定
    GIT命令操作
    Git简介
  • 原文地址:https://www.cnblogs.com/goodtest2018/p/13063536.html
Copyright © 2011-2022 走看看