# Leetcode学习笔记-556. 下一个更大元素 III

##### 556. 下一个更大元素 III

class Solution {
public:
static bool compare(int a,int b){
return a>b;
}
int nextGreaterElement(int n) {
int ncpy = n;
int digitcnt = 0;
int flag = 0;
int position = 0;
int temp, swap;
int result = 0;
string check;
vector<int> nums;
while(n) {
digitcnt++;
temp = n%10;
nums.push_back(temp);
n = n/10;
if(n) {
if((temp > (n%10))&&(!flag)) {
position = digitcnt;
flag++;
}
}
}
if(!flag) return -1;
else{
for(int i = 0;i < position;i++){
if(nums[i] > nums[position]){
swap = nums[position];
nums[position] = nums[i];
nums[i] = swap;
vector<int>::iterator right;
right = nums.begin();
for(int k = 0;k < position;k++) right++;
sort(nums.begin(), right, compare);
break;
}
}
}
vector<char> check1;
for(int i = nums.size();i > 0;i--) check1.push_back(nums[i-1] + '0');
check.insert(check.begin(), check1.begin(), check1.end());

if((check.size() >= 10)&&(check > "2147483647")) return (-1);
else{
for(int i = nums.size() ;i > 0;i--) result = result*10 + nums[i-1];
return result;
}
}
};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120