LeetCode第33天🐱‍🏍

·  阅读 344

326. 3的幂

// var isPowerOfThree = function(n) {
//     let b = 1
//     while (b < n) {
//         b = 3 * b
//     }
//     return b == n ? true : false
// };

var isPowerOfThree = function(n) {
    return n > 0 && 1162261467 % n === 0;
};
复制代码

200. 岛屿数量

经过实验发现没有必要添加数组判断是否遍历,反而使得空间复杂度变大,直接遍历原数组,将1置为0即可

function helper(grid, i, j, rows, cols) {
  if (i < 0 || j < 0 || i > rows - 1 || j > cols - 1 || grid[i][j] === "0")
    return;

  grid[i][j] = "0";

  helper(grid, i + 1, j, rows, cols);
  helper(grid, i, j + 1, rows, cols);
  helper(grid, i - 1, j, rows, cols);
  helper(grid, i, j - 1, rows, cols);
}

var numIslands = function(grid) {
  let res = 0;
  const rows = grid.length;
  if (rows === 0) return 0;
  const cols = grid[0].length;
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (grid[i][j] === "1") {
        helper(grid, i, j, rows, cols);
        res++;
      }
    }
  }
  return res;
};
复制代码

230. 二叉搜索树中第K小的元素

中序遍历 排序

var kthSmallest = function(root, k) {
    let i = 0;
    let val = null;
    travel(root);
    return val;

    function travel(node) {
        node.left && travel(node.left);

        if (++i === k) {
            val = node.val;
            return;
        }

        node.right && travel(node.right);
    }
};
复制代码
分类:
前端
收藏成功!
已添加到「」, 点击更改