zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第八章 数组和矩阵问题 最长的可整合子数组的长度...

    题目

    最长的可整合子数组的长度
    package com.lizhouwei.chapter8;
    
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * @Description: 最长的可整合子数组的长度
     * @Author: lizhouwei
     * @CreateDate: 2018/5/7 21:02
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter8_8 {
    
        public int getLIL(int[] arr) {
            Set<Integer> set = new HashSet<>();
            int max = 0;
            int min = 0;
            int res = 0;
            for (int i = 0; i < arr.length; i++) {
                max = Integer.MIN_VALUE;
                min = Integer.MAX_VALUE;
                for (int j = i; j < arr.length; j++) {
                    if (set.contains(arr[j])) {
                        break;
                    }
                    set.add(arr[j]);
                    max = Math.max(max, arr[j]);
                    min = Math.min(min, arr[j]);
                    if (max - min == j - i) {
                        res = Math.max(res, j - i + 1);
                    }
                }
                set.clear();
            }
            return res;
        }
        //测试
        public static void main(String[] args) {
            Chapter8_8 chapter = new Chapter8_8();
            int[] arr = {5, 5, 3, 2, 6, 4, 3};
            System.out.println("数组 arr = {5, 5, 3, 2, 6, 4, 3}中");
            System.out.println("最长的可整合子数组的长度为:" + chapter.getLIL(arr));
        }
    }
    

    结果

    1369004-20180507212655027-763746313.png

    转载于:https://www.cnblogs.com/lizhouwei/p/9005075.html

  • 相关阅读:
    es6之class继承
    es6-class基本语法
    vue-cli3搭建pwa项目(一)
    vue 组件的通信方式
    react之组件&props
    React之元素渲染
    JSX
    JSX
    在项目中怎么使用react
    认识react
  • 原文地址:https://www.cnblogs.com/twodog/p/12136964.html
Copyright © 2011-2022 走看看