题目
最长的可整合子数组的长度
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));
}
}
结果
转载于:https://www.cnblogs.com/lizhouwei/p/9005075.html