題目以下:java
將這個問題考慮三種狀況:git
1)若是輸入的正整數n的每一位都按照降序排列,則確定不存在知足題意的數,返回-1。例如54321算法
2)若是輸入的正整數n的每一位都按照升序排列,則只須要將最後兩位調換位置便可。例如123456→123465ide
3)其餘狀況,由於須要找知足題意的最小數,因此從右往左處理數字(即從低位到高位)spa
前兩種狀況容易完成,咱們來討論第三種狀況,也就是解決這道題的關鍵算法:圖片
Ⅰ. 從右往左遍歷整數的各個位,直到找到前一位的數字小於後一位的數字。好比,輸入的數爲:543976,則遍歷到3時中止,我將這個位置叫作中止位,由於3小於後一位9;若是找不到這樣的數,則該數不知足題意,返回-1ip
Ⅱ. 而後找到中止位右邊的位數中最小的數,將其與中止位交換。543976的中止位是3,3右邊的位數是976,位數中最小的數是6,因此將6與3交換,這樣就保證在中止位上的數是知足題意的最小數,it
Ⅲ. 而後將中止位右邊的位數按升序排列(將大數往低位放,從而獲得最小數)。好比543976 → 546973 → 546379,返回546379便可io
Java實現class
import java.lang.reflect.Array; import java.util.Arrays; /* *@author: David *@Time: 2018年5月24日下午5:01:08 *@Description: */ public class TheGreaterElement_IIIBter { private static int solution(int n) { char[] num = (n + "").toCharArray(); int i , j; //search the stop digit for(i = num.length - 1;i > 0;i--){ if(num[i] > num[i - 1]) break; } //if the digits sorted in descending order,then the result is impossible if(i == 0) return -1; //search the smallest digit on right size of (i - 1)th digit int x = num[i - 1]; int smallest = i; for( j = i + 1;j < num.length;j++) { if( num[j] > x && num[j] <= num[smallest]) smallest = j; } System.out.println(smallest); //swap the stop digit and the smallest digit on right size of stop digit char temp = num[i - 1]; num[i - 1] = num[smallest]; num[smallest] = temp; //Arrays.sort(int[] arr, int from_Index, int to_Index) //to sort an array of integers in ascending order. Arrays.sort(num,i,num.length); long val = Long.parseLong(new String(num)); return val > Integer.MAX_VALUE ? -1 : (int)val; } public static void main(String[] args) { int n = 543976; System.out.println(solution(n)); } }