12354 組合的數字 找比該數據最大中的最小數字
思路:
- 從後往前遍歷得到一個相鄰的後面比前面大的數據索引位置
- 從當前索引到數組最大位置建立兩個指針,left爲當前索引值var[left],right爲最大位置索引代表到值var[right],若val[right] > var[left]則交換
- 交換後繼續交換當前索引到數組最大位置建立兩個指針中間的值,因爲當前索引後面 前面大都比後面的數大
class MinMaxLargest {
public static void main(String[] args) {
int[] arr = new int[]{1,2,4,3,1};
final int point = findPoint(arr);
if(point != -1) {
getMinMax(arr, point);
System.out.println(Arrays.toString(arr));
}
}
private static int findPoint(int[] arr) {
for(int i = arr.length - 1; i > 0;i --) {
if(arr[i] > arr[i - 1]) {
return i;
}
}
return -1;
}
private static void getMinMax(int[] arr, int index) {
int left = arr[index - 1];
for(int i = arr.length - 1; i >= index;i --) {
int right = arr[i];
if(right > left) {
int temp = arr[i];
arr[i] = arr[index - 1];
arr[index - 1] = temp;
break;
}
}
for(int i = index,j = arr.length - 1; i < j; i++,j--) {
int temp = arr[index];
arr[index] = arr[j];
arr[j] = temp;
}
}
}