题目链接: https://leetcode.com/problems/next-greater-element-iii/description/
Description
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
Example 1:
Input: 12
Output: 21
Example 2:
Input: 21
Output: -1
解题思路
- 将整数拆分成一个个数字,从后往前寻找第一个比其后面数字小的位置,记为
keyPos
; - 寻找
keyPos
后面数字中,比其大的最小的数字,与之交换; - 将
keyPos
后面数字从小到大排序。
例子: 1346532
- 从后往前找 13**4**6532,找到
keyPos
为下标2,即数字4; - 将数字4与其后面的数字 6532 中比它大的最小的数字 5 交换,得到 13**5**6432;
- 将
keyPos
后面的数字,即 6432 从小到大排序得到结果,1352346
Code
class Solution {
public:
int nextGreaterElement(int n) {
vector<int> nums;
int temp = n;
long res = 0;
while (temp != 0) {
nums.push_back(temp % 10);
temp /= 10;
}
int keyPos = 1;
while (keyPos < nums.size() && nums[keyPos] >= nums[keyPos - 1]) keyPos++;
if (keyPos >= nums.size()) return -1;
int firstBigPos = keyPos - 1;
for (int i = firstBigPos - 1; i >= 0; --i) {
if (nums[i] > nums[keyPos] && nums[i] < nums[firstBigPos]) firstBigPos = i;
}
temp = nums[keyPos];
nums[keyPos] = nums[firstBigPos];
nums[firstBigPos] = temp;
sort(nums.begin(), nums.begin() + keyPos, [](int a, int b) {return a > b;});
for (int i = nums.size() - 1; i >= 0; --i) res = res * 10 + nums[i];
return res > INT_MAX ? -1 : res;
}
};