zoukankan      html  css  js  c++  java
  • 670. Maximum Swap

    Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

    Example 1:

    Input: 2736
    Output: 7236
    Explanation: Swap the number 2 and the number 7.
    

     Example 2:

    Input: 9973
    Output: 9973
    Explanation: No swap.
    

     Note:

    1. The given number is in the range [0, 108]

    只交换一次整数中的两个数,获得最大的值

    思路:从高位向低扫描,如果后面某位的数大于等于当前位的值,交换位置后即得到最大值。

     1     public int maximumSwap(int num) {
     2 //        从高位向低扫描,如果后面某位的数大于等于当前位的值,交换位置后即得到最大值
     3         char[] dig = String.valueOf(num).toCharArray();
     4         int maxIndex = 0;
     5         while (maxIndex < dig.length - 1) {
     6             int newMaxIndex = maxIndex;
     7             for (int i = maxIndex + 1; i < dig.length; i++) {
     8                 if (dig[newMaxIndex] <= dig[i])  newMaxIndex = i;
     9             }
    10             if (newMaxIndex != maxIndex && dig[newMaxIndex] != dig[maxIndex]) {
    11                 char temp = dig[newMaxIndex];
    12                 dig[newMaxIndex] = dig[maxIndex];
    13                 dig[maxIndex] = temp;
    14                 return Integer.valueOf(new String(dig));
    15             }else  maxIndex++;//当前maxIndex的后面没有大于等于它的数字了
    16         }
    17         return num;
    18     }
  • 相关阅读:
    log4j配置详解
    elasticsearch6.0版本安装head插件
    JAVA笔记-如何将百万级数据高效的导出到Excel表单
    抽象方法为什么不能被private与static修饰
    vue利用promise实现连续弹框
    vue代码片段
    h5元素高度超出屏幕但不滚动
    css3动画
    vue 引入静态图片404
    ios windows.open()不能打开
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7678791.html
Copyright © 2011-2022 走看看