[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

 

转载于:https://www.cnblogs.com/immjc/p/7803169.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值