算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从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);
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: