public class Solution { public int NextGreaterElement(int n) { char[] nums = n.ToString().ToCharArray(); int i = nums.Length - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; } if (i < 0) { return -1; } int j = nums.Length - 1; while (j >= 0 && nums...
下面这种解法博主感觉有些耍赖了,用到了STL的内置函数next_permutation,该数字实现的就是这样一个功能,找下一个全排序,刚好比当前的值大,贴上来权当好玩: 解法二: classSolution {public:intnextGreaterElement(intn) {stringstr =to_string(n); next_permutation(str.begin(), str.end());longlongres =stoll...
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...
returnnext == n || next > INT_MAX ? -1 : next; } }; C++: using next permutation 1 2 3 4 5 6 intnextGreaterElement(intn) { autodigits = to_string(n); next_permutation(begin(digits), end(digits)); autores = stoll(digits); return(res > INT_MAX || res <= n) ? -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 下一个较大的元素之三...
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 Case 1 Case 2...
Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. ...
【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位之后的字符应该从小到大...
举个例子:53421,从右往左遍历可以3小于其右侧的任何一个值,则将3和右侧最小的整数进行交换得到51423,再对1右侧的所有数字按照从小到大进行排序,则可以得出大于53421的最小正整数,即51234 代码如下: publicintnextGreaterElement(intn){ String value =String.valueOf(n);char[]digits = value.toCharArray();int...