• [LeetCode] 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]

    给定一个正整数,要求最多交换一次,使这个数最大。
    思路:
    如果要交换两个数,可以使用swap函数,这就需要将将num转化成整数数组或者字符串数组,方便起见利用to_string函数将num转换成字符串数组。
    因为如果要使交换后的数字最大,应该找出距离首位最近的的那个值(小于最大值)与距离首位最远的那个最大值。所以使用字符串逆序遍历,找出对应值及其索引。
    最后判断如果给定num不需要交换,则返回num。否则交换找出的数字后返回即可。

    class Solution {
    public:
        int maximumSwap(int num) {
            string str = to_string(num);
            int maxVal = -1, maxIdx = -1, leftIdx = -1, rightIdx = -1;
            for (int i = str.size() - 1; i >= 0; i--) {
                if (str[i] > maxVal) {
                    maxVal = str[i];
                    maxIdx = i;
                }
                if (str[i] < maxVal) {
                    leftIdx = i;
                    rightIdx = maxIdx;
                }
            }
            if (leftIdx == -1)
                return num;
            swap(str[leftIdx], str[rightIdx]);
            return stoi(str);
        }
    };
    // 3 ms
  • 相关阅读:
    【JAVA反射】自定义类加载器
    工厂模式+反射+泛型
    wsdl文件生成webservice代理类及使用生成的代理类
    WebApi 做接口遇到的问题总结
    region URL请求数据
    LinQ 创建连接、简单增删改查
    JS整理
    WebForm 全局对象、commend
    WebForm 内置对象、数据增删改、状态保持
    WebForm 控件(二)
  • 原文地址:https://www.cnblogs.com/immjc/p/7803169.html
Copyright © 2020-2023  润新知