调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
中等
相关标签
相关企业
提示

给你一个长度为 n 下标从 0 开始的整数数组 nums 。

你可以对 nums 执行特殊操作 任意次 (也可以 0 次)。每一次特殊操作中,你需要 按顺序 执行以下步骤:

  • 从范围 [0, n - 1] 里选择一个下标 i 和一个  整数 x 。
  • 将 |nums[i] - x| 添加到总代价里。
  • nums[i] 变为 x 。

如果一个正整数正着读和反着读都相同,那么我们称这个数是 回文数 。比方说,121 ,2552 和 65756 都是回文数,但是 24 ,46 ,235 都不是回文数。

如果一个数组中的所有元素都等于一个整数 y ,且 y 是一个小于 109 的 回文数 ,那么我们称这个数组是一个 等数数组 

请你返回一个整数,表示执行任意次特殊操作后使 nums 成为 等数数组 的 最小 总代价。

 

示例 1:

输入:nums = [1,2,3,4,5]
输出:6
解释:我们可以将数组中所有元素变为回文数 3 得到等数数组,数组变成 [3,3,3,3,3] 需要执行 4 次特殊操作,代价为 |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6 。
将所有元素变为其他回文数的总代价都大于 6 。

示例 2:

输入:nums = [10,12,13,14,15]
输出:11
解释:我们可以将数组中所有元素变为回文数 11 得到等数数组,数组变成 [11,11,11,11,11] 需要执行 5 次特殊操作,代价为 |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11 。
将所有元素变为其他回文数的总代价都大于 11 。

示例 3 :

输入:nums = [22,33,22,33,22]
输出:22
解释:我们可以将数组中所有元素变为回文数 22 得到等数数组,数组变为 [22,22,22,22,22] 需要执行 2 次特殊操作,代价为 |33 - 22| + |33 - 22| = 22 。
将所有元素变为其他回文数的总代价都大于 22 。

 

提示:

  • 1 <= n <= 105
  • 1 <= nums[i] <= 109
通过次数
4.4K
提交次数
18.4K
通过率
24.1%


相关企业

提示 1
Find the median of nums after sorting it (if the length is even, we can select any number from the two in the middle). Let’s call it m.

提示 2
Try the smallest palindromic number that is larger than or equal to m (if any) and the largest palindromic number that is smaller than or equal to m (if any). These two values are the candidate palindromic numbers for values of all indices.

提示 3
We can use math constructions to construct the two palindromic numbers in O(log(m) / 2) time or we can do it using brute-force by starting from m and checking smaller and larger values in O(sqrt(10log(m))).

提示 4
It is also possible to just generate all palindromic numbers using recursion in O(sqrt(109log(109)).


评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
运行和提交代码需要登录
nums =
[1,2,3,4,5]
Source