编辑
2023-12-09
算法题
00
请注意,本文编写于 518 天前,最后修改于 518 天前,其中某些信息可能已经过时。

题目

傻瓜暴力

cpp
class Solution { public: int nextBeautifulNumber(int n) { for (int i = ++n;; i++) { vector<int> m(10); int temp = i; while (temp > 0) { int x = temp % 10; temp /= 10; m[x]++; } bool flag = true; for (int j = 0; j < 10; j++) { if(m[j] != 0 && m[j]!=j) { //不能出现0 flag = false ; } } if(flag) { return i; } } } };

官解暴力

cpp
class Solution { public: bool isBalance(int x) { vector<int> count(10); while (x > 0) { count[x % 10]++; x /= 10; } for (int d = 0; d < 10; ++d) { if (count[d] > 0 && count[d] != d) { return false; } } return true; } int nextBeautifulNumber(int n) { for (int i = n + 1; i <= 1224444; ++i) { if (isBalance(i)) { return i; } } return -1; } };

Go

go
func isBalance(x int) bool { count := make([]int, 10) for x > 0 { count[x % 10]++ x /= 10 } for i := 0; i < 10; i++ { if count[i] > 0 && count[i] != i { return false } } return true } func nextBeautifulNumber(n int) int { for i := n + 1; i <= 1224444; i++ { if isBalance(i) { return i } } return -1 }

Java

go
class Solution { public int nextBeautifulNumber(int n) { for (int i = n + 1; i <= 1224444; ++i) { if (isBalance(i)) { return i; } } return -1; } private boolean isBalance(int x) { int[] count = new int[10]; while (x > 0) { count[x % 10]++; x /= 10; } for (int d = 0; d < 10; ++d) { if (count[d] > 0 && count[d] != d) { return false; } } return true; } }

python

python
class Solution: def nextBeautifulNumber(self, n: int) -> int: for i in range(n + 1, 1224445): count = Counter(str(i)) if all(count[d] == int(d) for d in count): return i

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!