LeetCode670. Maximum Swap

原题:https://leetcode.com/problems/maximum-swap/description/


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:
The given number is in the range [0, 10^8]


题目要求交换两位数使得交换后数最大。要使得数最大,首先就考虑最高位的交换,但最高位可能已经是最大的数,所以问题就转变为:
使能替换的最高位的数替换为一个剩下低位数里面最大的数。
从最高位开始遍历,对于每个当前遍历到的数,再从低位开始遍历剩下的数,找到其中最大的一个。
如果找到的数大于当前高位的数,则将其替换;如果没有比当前高位遍历的数更大的数,则高位继续遍历到其低一位重复以上过程。,


class Solution {
public:
    int maximumSwap(int num) {
        stringstream ss;
        ss << num;
        string s = ss.str();
        for (int i = 0; i < s.size(); i++) {
            int max = 0,pos = 0;
           for (int j = s.size(); j > i; j--) {
               if (s[j] - '0' > max) {
                   max = s[j] - '0';
                   pos = j;
               }
           }
            if (max > s[i] - '0') {
                char tmp = s[i];
                s[i] = s[pos];
                s[pos] = tmp;
                stringstream sss(s);
                sss >> num;
                return num;
            }
        }
        return num;
    }
};

111 / 111 test cases passed.
Status: Accepted
Runtime: 3 ms
Submitted: 8 minutes ago

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值