給定一個無序數組arr,求出須要排序的最短子數組長度。java
例如:arr=[1, 5, 3, 4, 2, 6, 7], 返回4,由於只有[5, 3, 4, 2]須要排序。數組
*spa
時間複雜度爲O(N), 空間複雜度爲O(1)code
/** * Created by liang on 2018/5/8. */ public class GetMinLength { public static void main(String[] args) { int[] arr = {1, 5, 3, 4, 2, 6, 7}; int result = getMinLength(arr); System.out.println("result: " + result); } public static int getMinLength(int[] arr) { if (arr == null || arr.length < 2) { return 0; } int min = arr[arr.length - 1]; int noMinIndex = -1; for (int i= arr.length - 2; i != -1; i--) { if (arr[i] > min) { noMinIndex = i; } else { min = Math.min(min, arr[i]); } } if (noMinIndex == -1) { return 0; } System.out.println("noMinIndex: " + noMinIndex); int max = arr[0]; int noMaxIndex = -1; for (int i=1; i != arr.length; i++) { if (arr[i] < max) { noMaxIndex = i; } else { max = Math.max(max, arr[i]); } } System.out.println("noMaxIndex: " + noMaxIndex); return noMaxIndex - noMinIndex + 1; } }
運行結果:排序
noMinIndex: 1 noMaxIndex: 4 result: 4