556. Next Greater Element III // GG
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:
Input: 12 Output: 21
Example 2:
21
-1
/**
* @param {number} n
* @return {number}
*/
var nextGreaterElement = function(n) {
var temp = n;
var arr = (""+n).split("");
var arr2 = (""+temp).split(""); //原序
var arr3 = arr.sort().reverse(); // 大至小
//arr.reverse();
var s = Number(arr3.join("")); //大
var s2 = Number(arr2.join("")); // 原
//var t = typeof(s);
//return (console.log(arr+":"+arr2+":"+arr3+":"+s+":"+s2+":"+t));
if(s2>s2){
// var t = typeof(s);
return(s);
}else{
return(-1);
}
};
找次大的排列 而不適最大的 QQ
需要從原序下手
從最右邊開始判斷
判斷右1是否大於右2
是的話 交換
不是的畫 和 左邊
留言
張貼留言