1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
next-greater-element-iii.cpp 1.22 KB
一键复制 编辑 原始数据 按行查看 历史
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助