[leetcode] 670. Maximum Swap

441 篇文章 0 订阅
284 篇文章 0 订阅

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:

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

分析

题目的意思是:我们有一次机会可以置换该数字中的任意两位,让我们返回置换后的最大值,当然如果当前数字就是最大值,我们也可以选择不置换,直接返回原数。

  • 将所有可能的置换都进行一遍,然后更新结果res,取其中较大的数字,这样一定会得到置换后的最大数字,这里使用了整型数和字符串之间的相互转换。

代码

class Solution {
public:
    int maximumSwap(int num) {
        string str=to_string(num);
        int res=num;
        for(int i=0;i<str.size();i++){
            for(int j=i+1;j<str.size();j++){
                swap(str[i],str[j]);
                res=max(res,stoi(str));
                swap(str[i],str[j]);
            }
        }
        return res;
    }
};

代码二(python)

  • 从后向前遍历,如果遇到更大的值maxValue,那么保存这个值的下标(index)和值(value)
  • 如果在这个值的左边遇到比maxValue小的数,那么保存对应的值leftValue和leftIndex,并将maxIndex赋予给rightiIndex,leftIndex和rightIndex这两个配对组成一组候选值
  • 从右向左遍历数组,遇到满足上述条件的值就覆盖更新对应的值,最后交换leftIndex和rightIndex下标对应的数即可
class Solution:
    def maximumSwap(self, num: int) -> int:
        s=list(str(num))
        maxVal=-1
        maxIdx=-1
        n=len(s)
        leftIdx=-1
        rightIdx=-1
        for i in range(n-1,-1,-1):
            if(maxVal<int(s[i])):
                maxVal=int(s[i])
                maxIdx=i
            if(int(s[i])<maxVal):
                leftIdx=i
                rightIdx=maxIdx
        
        s[leftIdx],s[rightIdx]=s[rightIdx],s[leftIdx]
        return ''.join(s)

参考文献

Maximum Swap 最大交换

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值