classSolution { public: intnextGreaterElement(int n){ int a[11], len = 0; while (n > 0) { a[++len] = n % 10; n /= 10; } a[0] = INT_MIN; int ok = 0; for (int i = 1; i <= len; ++i) { if (a[i] < a[i-1]) { int idx = upper_bound(a+1, a+i, a[i]) - a; swap(a[idx], a[i]); for (int j = 1; j <= (i-1)/2; ++j) { swap(a[j], a[i-j]); } ok = 1; break; } } if (!ok) return-1; long res = 0; for (int i = len; i > 0; --i) { res = res * 10 + a[i]; } return res > INT_MAX ? -1 : res; } };
python
classSolution: defnextGreaterElement(self, n: int) -> int: s = str(n) n = len(s) res = '' for i inrange(n-1, -1, -1): res = s[i] + res if i < n-1and res[0] < res[1]: res = ''.join(sorted(res)) for j inrange(n-i): if res[j] > s[i]: res = res[j] + res[:j] + res[j+1:] break s = s[:i] + res returnint(s) ifint(s) < pow(2, 31) else -1 return -1
后记
这题还可以直接用 c++ 标准库函数 next_permutation 直接生成下一个更大的字符串排列,然后转换成整数就行了,代码如下:
classSolution { public: intnextGreaterElement(int n){ string s = to_string(n); next_permutation(s.begin(), s.end()); long res = stoll(s); return res > INT_MAX || res <= n ? -1 : res; } };