0556.cpp (693B)
1 class Solution { 2 public: 3 int nextGreaterElement(int n) { 4 string nums = to_string(n); 5 6 int prev = 0; 7 stack<int> st; 8 for (int i = nums.size() - 1; i >= 0; i--) { 9 if (!st.empty() && nums[i] < nums[st.top()]) { 10 while (!st.empty() && nums[i] < nums[st.top()]) { 11 prev = st.top(); 12 st.pop(); 13 } 14 swap(nums[i], nums[prev]); 15 reverse(nums.begin() + i + 1, nums.end()); 16 break; 17 } 18 st.push(i); 19 } 20 21 long long res = stoll(nums); 22 return (res > INT_MAX || (int)res == n) ? -1 : (int)res; 23 } 24 };