码迷,mamicode.com
首页 > 其他好文 > 详细

【字符串】556. 下一个更大元素 III

时间:2020-05-04 13:39:01      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:mamicode   reverse   com   turn   pre   nbsp   iii   字符   while   

题目:

技术图片

 

 

解答:

技术图片

 

 

 1 class Solution {
 2 public:
 3      vector<int> digits(int n) 
 4      {
 5         vector<int> res;
 6         while (n > 0) 
 7         {
 8             res.push_back(n % 10);
 9             n /= 10;
10         }
11         reverse(res.begin(), res.end());
12         return res;
13     }
14     int nextGreaterElement(int n) 
15     {
16         vector<int> nums = digits(n);
17         int N = nums.size();
18         int l = -1;
19         for (int i = 1; i < N; ++i) 
20         {
21             if (nums[i] > nums[i - 1]) 
22             {
23                 l = i - 1;
24             }
25         }
26         if (l == -1) 
27         {
28             return -1;
29         }
30 
31         reverse(nums.begin() + l + 1, nums.end());
32         int r = upper_bound(nums.begin() + l + 1, nums.end(), nums[l]) - nums.begin();
33         swap(nums[l], nums[r]);
34         long res = 0;
35         for (int i = 0; i < N; ++i) 
36         {
37             res = 10 * res + (long)nums[i];
38         }
39         return res > INT_MAX ? -1 : res;
40     }
41 };

 

【字符串】556. 下一个更大元素 III

标签:mamicode   reverse   com   turn   pre   nbsp   iii   字符   while   

原文地址:https://www.cnblogs.com/ocpc/p/12826096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!