​LeetCode刷题实战564:寻找最近的回文数

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 寻找最近的回文数,我们先来看题面:

https://leetcode-cn.com/problems/find-the-closest-palindrome/

Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.

The closest is defined as the absolute difference minimized between two integers.

给定一个表示整数的字符串 n ,返回与它最近的回文整数(不包括自身)。如果不止一个,返回较小的那个。

“最近的”定义为两个整数差的绝对值最小。

示例                         

示例 1:

输入: n = "123"
输出: "121"

示例 2:

输入: n = "1"
输出: "0"
解释: 0 和 2是最近的回文,但我们返回最小的,也就是 0。

解题

https://leetcode.com/problems/find-the-closest-palindrome/discuss/102391/python-simple-with-explanation

思路:比较5个数就可以了,假设n的位数为k

1.比较9....9 (1e(k-1) - 1) 

e.g. 10001 -> 9999

2.比较10...01 (1e(k) + 1)

e.g. 99999 -> 100001

3.n[0...(k+1)/2] + {1/0/-1},再镜像构成的数

e.g.

12932 {12921/12821/13031} ->12921

99800 {99899/99799/99999} -> 99799

99099 {99099/98989/99199} -> 99199

NOTE1 不能取n本身

NOTE2 如果有两个数都是离n最近, 取较小的数

class Solution {
public:
    string nearestPalindromic(string n) {

        using LL = long long;
        vector<LL> nums;

        int k = n.size();
        unordered_set<LL> S;
        // 1.插入5个数
        S.insert((LL) pow(10, k - 1) - 1);
        S.insert((LL) pow(10, k) + 1);
        for (LL i: {1, 0, -1})
        {
            // 1234 12345
            string left = to_string(stol(n.substr(0, k / 2 + (k & 1))) + i);
            S.insert(stol(left + string(left.rbegin() + (k & 1), left.rend())));
        }
        // 2.不能用n
        LL nn = stol(n);
        S.erase(nn);
        // 3.比较距离
        LL minv = std::numeric_limits<LL>::max();
        LL res = std::numeric_limits<LL>::max();
        for (LL num: S)
        {
            LL diff = abs(num - nn);
            if (diff < minv || diff == minv && num < res)
                minv = abs(num - nn), res = num;
        } 
        return to_string(res);
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-560题汇总,希望对你有点帮助!

LeetCode刷题实战561:数组拆分 I

LeetCode刷题实战562:矩阵中最长的连续1线段

LeetCode刷题实战563:二叉树的坡度

1510371ab3906edd9dd918dfeff6c303.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值