(算法分析Week10)Maximum Swap[Meduim]

670. Maximum Swap[Medium]

题目来源

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.
Example1:

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

Example2:

Input: 9973
Output: 9973
Explanation: No swap.

The given number is in the range [0, 10^8]

Solution

给出一个数字,可以选择其中任意两个数交换一次,使得交换完的数是所有交换选择中最大的那个。
显而易见,肯定是把所有数字中最大的那个放在最高位,如果高位已经不能再大,那就次一位,以此类推。
思路就是用一个整数数组把整个数字按位存放,然后从第一位开始向后比较,找出从当前数字往后找比它大的最大值,然后交换。最后再把数组转成string返回即可。
要注意一些比较坑的地方,比如输入1993,如果从1开始往后找到第一个9就返回交换,那就得不到期望的9913的结果。所以判断条件不能是大于,而应该是大于等于,目的是找到处于相对最低位的最大值。

Complexity analysis

O(n²)

Code

class Solution {
public:
    int maximumSwap(int num) {
        vector<int> result;
        while (num) {
            result.push_back(num % 10);
            num /= 10;
        }
        bool flag = false;
        for (int i = result.size() - 1; i >= 0 && flag == false; i--) {
            int index = i;
            int max = result[i];
            for (int j = i - 1; j >= 0 && flag == false; j--) {
                if (max <= result[j]) {
                    max = result[j];
                    index = j;
                }

            }
            if (result[i] < result[index]) {
                int temp = result[i];
                result[i] = result[index];
                result[index] = temp;
                flag = true;
            }
        }
        int t = 0;

        for (int i = result.size() - 1; i >= 0; i--) {
            t *= 10;
            t += result[i];
        }
        return t;
    }
};

Result

这里写图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值