代码拉取完成,页面将自动刷新
// Time: O(logn) = O(1)
// Space: O(logn) = O(1)
class Solution {
public:
int nextGreaterElement(int n) {
auto digits = to_string(n);
nextPermutation(begin(digits), end(digits)); // self-implemented next_permutattion()
auto result = stoll(digits);
return (result > numeric_limits<int>::max() || result <= n) ? -1 : result;
}
private:
template<typename BidiIt>
bool nextPermutation(BidiIt begin, BidiIt end) {
const auto rbegin = reverse_iterator<BidiIt>(end);
const auto rend = reverse_iterator<BidiIt>(begin);
// Find the first element (pivot) which is less than its successor.
auto pivot = next(rbegin);
while (pivot != rend && *pivot >= *prev(pivot)) {
++pivot;
}
bool is_greater = true;
if (pivot != rend) {
// Find the number which is greater than pivot, and swap it with pivot
auto change = find_if(rbegin, pivot, bind1st(less<int>(), *pivot));
swap(*change, *pivot);
} else {
is_greater = false;
}
// Make the sequence after pivot non-descending
reverse(rbegin, pivot);
return is_greater;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。