classSolution {public:intnextGreaterElement(intn) {stringstr =to_string(n);intlen = str.size(), i = len -1;for(; i >0; --i) {if(str[i] > str[i -1])break; }if(i ==0)return-1;for(intj = len -1; j >= i; --j) {if(str[j] > str[i -1]) { swap(str[j], ...
publicintnextGreaterElement(int n){String value=String.valueOf(n);char[]digits=value.toCharArray();int i=digits.length-1;//找到小于右侧任意值的第一个正整数while(i>0){if(digits[i-1]<digits[i]){break;}i--;}if(i==0){return-1;}//找到该整数右侧大于该整数的最小整数int maxIndex=i,j...
intnextGreaterElement(intn) { string s = to_string(n); if(s.length() == 1) { return-1; } /* find the first decreasing digit from the right, eg: 59876, 5 is the first decreasing digit */ inti = s.length() - 2;// 21 -> i = 0; 59876 -> i = 3 for(; i >= 0 &&...
Test Result Subscribe to unlock. Thanks for using LeetCode! To view this solution you must subscribe to premium. Subscribe C++ Auto 1 2 3 4 5 6 class Solution { public: int nextGreaterElement(int n) { } }; Saved Ln 1, Col 1 ...
return res> INT_MAX ? -1:res; } }; 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 参考文献 [LeetCode] Next Greater Element III 下一个较大的元素之三...
【Leetcode】556. Next Greater Element III 1 要注意结果,因为可能结果超出32bit能表示的范围了 2 思路是https://leetcode.com/problems/next-greater-element-iii/discuss/101824/Simple-Java-solution-(4ms)-with-explanation.
Leetcode 556. Next Greater Element III 1. Description 2. Solution **解析:**Version 1,先将数字n变为字符数组,要找最小的大于n的数,则应该从右往左开始,依次寻找第i位字符右边的大于当前字符的最小数字,然后互换二者位置,由于新数字的第i位字符大于n中的第i位字符,因此新数字i位之后的字符应该从小到大...
classSolution{publicintnextGreaterElement(intn){char[]digits=Integer.toString(n).toCharArray();intlen=digits.length;// I) Start from the right most digit and// find the first digit that is// smaller than the digit next to it.inti=len-1;while(i>0&&digits[i-1]>=digits[i]){--i;}/...
503. Next Greater Element II 难度:m class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: if not nums: return [] stack = [] res = [-1]*len(nums) for i in range(len(nums)): while stack and nums[stack[-1]]<nums[i]: ...
解题思路 找出一个循环数组中右边第一个比它大的数,与496.Next Greater Element I不同,这道题可以再从从头找一遍。所以循环两次即可,其他的方面没有变化。 时间复杂度:O(n * 2) / 空间复杂度:O(n)栈空间 classSolution{public:vector<int>nextGreaterElements(vector<int>&nums){constintsize=nums.size()...