我试图在这里解决这个leetcode问题:https://leetcode.com/problems/next-closest-time/description/。
我的解决方案是尝试每个有效的组合,然后将我的ans变量设置为最接近原始时间的变量。它会打印出所有组合,但diff变量永远不会改变。在for循环之后(如果cur.length == 4)它会打印每个可能的组合,因为它仍然认为diff是9007199254740991.此外,当我将ans分配给cur.slice()时,我收到一个空白数组。即使我在nextClosestTime函数中取消注释它,我仍然有同样的问题。
/**
* @param {string} time
* @return {string}
*/
var diff = 9007199254740991;
function calcSeconds(digits) {
var hours = (digits[0] * 10) + digits[1];
var seconds = (digits[2] * 10) + digits[3];
return (hours * 3600) + (seconds * 60);
}
function nextClosestTime(time) {
var digits = [];
// diff = 9007199254740991;
var cur = [];
var ans = [];
for (var i = 0; i < time.length; i++) {
if (isFinite(time.charAt(i))) {
digits.push(parseInt(time.charAt(i)));
}
}
var target = calcSeconds(digits);
nch(digits, cur, diff, target, ans);
return ans;
};
function nch(digits, cur, diff, target, ans) {
if (cur.length == 4) {
var curSec = calcSeconds(cur);
if (Math.abs(curSec - target) < diff) {
console.log(cur);
diff = Math.abs(calcSeconds(digits) - calcSeconds(cur));
//ans = cur.slice();
}
return;
}
for (var i = 0; i < digits.length; i++) {
if ((((cur[0] * 10) + cur[1]) >= 24) || (((cur[2] * 10) + cur[3]) >= 60)) {
return;
}
cur.push(digits[i]);
nch(digits, cur, diff, target, ans);
cur.pop()
}
}