Next Greater Element III
第9天了。
今天的题目是 Next Greater Element III :
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:
1  | Input: 12  | 
Example 2:
1  | Input: 21  | 
这道题我的解法是:
- 先将数字转换成数组,由于是除法和取余解析出来的数组,所以整个数组是倒过来的,即
123得到[3,2,1] - 从前向后遍历找到第一个逆序(即
vec[i-1] > vec[i)的情况。 - 从
vec[0: i]找到第一个小于等于vec[i]的元素vec[j]。 - 交换
vec[i]和vec[j],然后将vec[0: i]逆序。 - 将
vec转换回数字,最后判断一下是否溢出即可。 
1  | int nextGreaterElement(int n) {  | 
其实写到这里基本上发现,这道题就是找全排列中的下一个元素,而这个功能,在C++中提供了一个好用的函数:next_permutation,所以我们可以先用to_string转换成字符数组,然后用next_permutation来解这道题:
1  | int nextGreaterElement(int n) {  |