题目
需要排序的最短子数组长度
java代码
package com.lizhouwei.chapter8;
/**
* @Description: 需要排序的最短子数组长度
* @Author: lizhouwei
* @CreateDate: 2018/4/29 8:03
* @Modify by:
* @ModifyDate:
*/
public class Chapter8_5 {
public int getMinLength(int[] arr) {
if (arr == null || arr.length < 2) {
return 0;
}
int minIndex = -1;
int min = arr[arr.length - 1];
for (int i = arr.length - 2; i > -1; i--) {
if (arr[i] > min) {
minIndex = i;
} else {
min = Math.min(min, arr[i]);
}
}
if (minIndex == -1) {
return 0;
}
int maxIndex = -1;
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < max) {
maxIndex = i;
} else {
max = Math.max(max, arr[i]);
}
}
return maxIndex - minIndex + 1;
}
//测试
public static void main(String[] args) {
Chapter8_5 chapter = new Chapter8_5();
int[] arr = {1, 5, 3, 4, 2, 6, 7};
int res = chapter.getMinLength(arr);
System.out.print("{1, 5, 3, 4, 2, 6, 7 }中需要排序的最大长度:" + res);
}
}
结果
原文地址:https://www.cnblogs.com/lizhouwei/p/8970336.html
时间: 2024-11-08 13:28:05