ACM之下一个更大元素

题目以下:java

图片.png


将这个问题考虑三种状况: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));
          
     }
}
相关文章
相关标签/搜索