《程序員代碼面試指南》第八章 數組和矩陣問題 需要排序的最短子數組長度
阿新 • • 發佈:2018-04-29
for package ret else rip RR pre public pub
題目
需要排序的最短子數組長度
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); } }
結果
《程序員代碼面試指南》第八章 數組和矩陣問題 需要排序的最短子數組長度