题目如下:

spacer.gif图片.png


将这个问题考虑三种情况:

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 digitfor(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 impossibleif(i == 0) return -1;//search the smallest digit on right size of (i - 1)th digitint 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 digitchar 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));}
}