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));
        }
    }
    
    

    结果

  • 相关阅读:
    LeetCode【125. 验证回文串】
    LeetCode【122. 买卖股票的最佳时机 II】
    LeetCode【121. 买卖股票的最佳时机】
    LeetCode【119. 杨辉三角 II】
    LeetCode【118. 杨辉三角】
    LeetCode【112. 路径总和】
    PAT1024
    PAT1020
    PAT1018
    PAT1017
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/9005075.html
Copyright © 2011-2022 走看看