LeetCode #670. Maximum Swap

本文介绍了一种通过交换数字中的两个位来获得最大可能数值的算法。在给定一个非负整数的情况下,该算法将尝试进行一次数字位的交换,以得到最大的数值结果。文章提供了详细的算法实现,包括如何确定可以交换的数字位以及如何执行交换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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]
class Solution {
public:
    int maximumSwap(int num) {
        string s=to_string(num);
        int i=-1, j=-1;
        int max_index=s.size()-1;
        // 从字符串末尾开始遍历
        for(int k=s.size()-2;k>=0;k--)
        {   // 如果能找到k使得k小于当前最大值,说明已经找到一对可以交换的数字
            if(s[k]<s[max_index])
            {
                i=k;
                j=max_index;
            } 
            // 找到了更大的数字,但是不确定是否有可以交换的另一个数字,所以先更新下标
            else if(s[k]>s[max_index]) max_index=k;
        }
        if(i!=-1) swap(s[i],s[j]);
        return stoi(s);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值