題目鏈接: 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;
}
};