題目如下:
將這個問題考慮三種情況:
1)如果輸入的正整數n的每一位都按照降序排列,則肯定不存在滿足題意的數,返回-1。例如54321
2)如果輸入的正整數n的每一位都按照升序排列,則只需要將最後兩位調換位置即可。例如123456→123465
3)其他情況,因爲需要找滿足題意的最小數,所以從右往左處理數字(即從低位到高位)
前兩種情況容易完成,我們來討論第三種情況,也就是解決這道題的關鍵算法:
Ⅰ. 從右往左遍歷整數的各個位,直到找到前一位的數字小於後一位的數字。比如,輸入的數爲:543976,則遍歷到3時停止,我將這個位置叫做停止位,因爲3小於後一位9;如果找不到這樣的數,則該數不滿足題意,返回-1
Ⅱ. 然後找到停止位右邊的位數中最小的數,將其與停止位交換。543976的停止位是3,3右邊的位數是976,位數中最小的數是6,所以將6與3交換,這樣就保證在停止位上的數是滿足題意的最小數,
Ⅲ. 然後將停止位右邊的位數按升序排列(將大數往低位放,從而得到最小數)。比如543976 → 546973 → 546379,返回546379即可
Java實現
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)); } }