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     }
  • 相关阅读:
    logging- 日志记录
    apscheduler -定时任务
    mysql
    Time-python
    pandas 常用语句
    re 正则
    sublime text3的快捷键
    git 常用操作
    tf.nn的conv2d卷积与max_pool池化
    WebApi 接口返回值类型详解 ( 转 )
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7678791.html
Copyright © 2011-2022 走看看