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

  • 相关阅读:
    第1章 引论
    Java反射
    用户职责菜单请求组
    API及接口清单
    独立值集导入脚本
    报表对应程序包查询
    正则表达式
    合并工作表
    去重
    分割表
  • 原文地址:https://www.cnblogs.com/twodog/p/12136964.html
Copyright © 2011-2022 走看看