66. Plus one

Leetcode-cn.com/problems/pl…

/** * @param {number[]} digits * @return {number[]} */ var plusOne = function (digits) { for(let i=digits.length -1; i>-1; i--){ digits[i] = (digits[i] + 1) % 10 if(digits[i] ! == 0){ return digits } } digits = [...Array(digits.length + 1)].map(_=>0) digits[0] = 1 return digits };Copy the code
/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function (digits) {
    let flag = 1
    for (let i = digits.length - 1; i >= 0; i--) {
        if (flag) {
            const target = digits[i] + flag
            if (target === 10) {
                digits[i] = 0
            }else{
                digits[i] = target
                flag --
                return digits
            }
        }
    }
    if(flag) {
        digits.unshift(flag)
    }
    return digits
};
Copy the code

815. Bus routes

Leetcode-cn.com/problems/bu…

  • BFS diffuses associated stations
/** * @param {number[][]} routes * @param {number} S * @param {number} T * @return {number} */ var numBusesToDestination  = function (routes, S, T) { if (S === T) { return 0 } let minTime = 0 const stack = [S] const visted = [] const relatedMap = {} for (let i = 0;  i < routes.length; i++) { for (let j = 0; j < routes[i].length; j++) { if (! RelatedMap [routes[I][j]]) {relatedMap[routes[I][j]] = new Set()} relatedMap[routes[I][j]].add(I)} // Add (I) while (stack.length) { minTime++ const size = stack.length for (let i = 0; i < size; i++) { const data = stack.shift() if (data === T) { return minTime } const relatedRoutes = relatedMap[data] for (let nextRoutes of relatedRoutes) { for (let nextStation of routes[nextRoutes]) { if (nextStation === T) { return minTime } if (! visted[nextStation]) { visted[nextStation] = true stack.push(nextStation) } } } } } return -1 };Copy the code
  • The line associated with BFS diffusion timed out
/** * @param {number[][]} routes * @param {number} S * @param {number} T * @return {number} */ var numBusesToDestination  = function (routes, S, T) { if(S===T){ return 0 } let minTime = 0 const stack = [] const visted = [] for (let i = 0; i < routes.length; i++) { for (let j = 0; j < routes[i].length; j++) { if (routes[i][j] === S) { if (routes[i].indexOf(T) >= 0) { return 1 } else { stack.push({ data: routes[i], index: i }) } } } } while (stack.length) { minTime++ const size = stack.length for (let i = 0; i < size; i++) { const { data, index } = stack.shift() if (data.indexOf(T) >= 0) { return minTime } else { for (let m = 0; m < routes.length; m++) { if (m ! == index) { if (isRelated(data, routes[m]) && ! visted[m]) { visted[m] = true stack.push({ data: routes[m], index: m }) } } } } } } function isRelated(l1, l2) { for (let i = 0; i < l1.length; i++) { if (l2.indexOf(l1[i]) >= 0) { return true } } return false } return -1 };Copy the code