Every day a Leetcode
题目来源:2048. 下一个更大的数值平衡数
解法1:枚举
这种题不能想复杂了,枚举大法好。
代码:
/*
* @lc app=leetcode.cn id=2048 lang=cpp
*
* [2048] 下一个更大的数值平衡数
*/
// @lc code=start
class Solution
{
public:
int nextBeautifulNumber(int n)
{
for (int i = n + 1; i <= 1000000000; i++)
if (isBalancedNumber(i))
return i;
return -1;
}
// 辅函数 - 判断一个数是否是数值平衡数
bool isBalancedNumber(int x)
{
vector<int> digitCount(10, 0);
while (x)
{
digitCount[x % 10]++;
x /= 10;
}
for (int i = 0; i < 10; i++)
if (digitCount[i] && digitCount[i] != i)
return false;
return true;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(C−n),其中 C = 1224444 是可能为答案的最大的数值平衡数,取决于题目的数据范围。
空间复杂度:O(DIGITS),用到了一个存储数位个数的数组,DIGITS = 10。其实就是 O(1)。
解法2:打表 + 二分查找
代码:
class Solution {
public:
const vector<int> balance {
1, 22, 122, 212, 221, 333, 1333, 3133, 3313, 3331, 4444,
14444, 22333, 23233, 23323, 23332, 32233, 32323, 32332,
33223, 33232, 33322, 41444, 44144, 44414, 44441, 55555,
122333, 123233, 123323, 123332, 132233, 132323, 132332,
133223, 133232, 133322, 155555, 212333, 213233, 213323,
213332, 221333, 223133, 223313, 223331, 224444, 231233,
231323, 231332, 232133, 232313, 232331, 233123, 233132,
233213, 233231, 233312, 233321, 242444, 244244, 244424,
244442, 312233, 312323, 312332, 313223, 313232, 313322,
321233, 321323, 321332, 322133, 322313, 322331, 323123,
323132, 323213, 323231, 323312, 323321, 331223, 331232,
331322, 332123, 332132, 332213, 332231, 332312, 332321,
333122, 333212, 333221, 422444, 424244, 424424, 424442,
442244, 442424, 442442, 444224, 444242, 444422, 515555,
551555, 555155, 555515, 555551, 666666, 1224444
};
int nextBeautifulNumber(int n) {
return *upper_bound(balance.begin(), balance.end(), n);
}
};