Skip to content

Instantly share code, notes, and snippets.

@HelKyle
Last active April 30, 2023 02:21
Show Gist options
  • Select an option

  • Save HelKyle/86d5f314a191f2688d06a5094251d3e3 to your computer and use it in GitHub Desktop.

Select an option

Save HelKyle/86d5f314a191f2688d06a5094251d3e3 to your computer and use it in GitHub Desktop.
Leetcode Javascript Utils
// 二分找下限
function lower_bound(nums, target) {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] >= target) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
// 二分找上限
function upper_bound(nums, target) {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] > target) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
// 并查集
class UnionFind {
constructor (n) {
this.parent = new Array(n).fill(0).map((element, index) => index);
this.size = new Array(n).fill(1);
// 当前连通分量数目
this.setCount = n;
}
findset (x) {
if (this.parent[x] === x) {
return x;
}
this.parent[x] = this.findset(this.parent[x]);
return this.parent[x];
}
unite (a, b) {
let x = this.findset(a), y = this.findset(b);
if (x === y) {
return false;
}
if (this.size[x] < this.size[y]) {
[x, y] = [y, x];
}
this.parent[y] = x;
this.size[x] += this.size[y];
this.setCount -= 1;
return true;
}
connected (a, b) {
const x = this.findset(a), y = this.findset(b);
return x === y;
}
}
// BigInt 支持 N 次方
let L = 2n ** BigInt(p)
// 大整数快 pow + mod
const mod = BigInt(1e9 + 7)
function pow(b, p) {
if (p === 0n) return 1n
if (p === 1n) return b
if (p % 2n) {
return pow(b, p - 1n) * b % mod
}
let h = pow(b, p / 2n)
return h * h % mod
}
// 二分取中间
const mid = l + ((r - l) >> 1);
// 最大公约数
function gcd (a, b) {
if (a % b === 0) {
return b
}
return gcd(b, a % b)
}
// 最小公倍数
function lcm(a,b){
return (a*b) / gcd(a,b);
}
@HelKyle
Copy link
Author

HelKyle commented Oct 18, 2021

字典树

class TrieNode {
    constructor() {
        this.children = new Array(26).fill(0);
        this.isEnd = false;
    }

    insert(word) {
        let node = this;
        for (let i = 0; i < word.length; i++) {
            const ch = word[i];
            const index = ch.charCodeAt() - 97;
            if (node.children[index] === 0) {
                node.children[index] = new TrieNode();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    includes (word) {
        let node = this;
        for (let i = 0; i < word.length; i++) {
            const ch = word[i];
            const index = ch.charCodeAt() - 97;
            if (!node || !node.children[index]) {
                return false
            }
            node = node.children[index];
        }
        return node.isEnd
    }

    getChildren() {
        return this.children;
    }

    isEnd() {
        return this.isEnd;
    }
}

@HelKyle
Copy link
Author

HelKyle commented Feb 20, 2022

function lowbit (x) {
	return x & -x
}

function highbit(i) {
    i |= (i >>  1);
    i |= (i >>  2);
    i |= (i >>  4);
    i |= (i >>  8);
    i |= (i >> 16);
    return i - (i >>> 1);
}

function bitMask (highbit, lowbit) {
   const i = ~0;
   return ~(i << highbit << 1) & (i << lowbit);
}

function bitCount(num) {
	let ans = 0
    for (let i = 0; i < 31; i ++) {
		if (num & (1 << i)) {
			ans ++
        }
    }
    return ans
}

function removeLastBit(num) {
   return num & (num - 1)
}

function appendLastBit(num) {
	return num | (num + 1)
}

@HelKyle
Copy link
Author

HelKyle commented Apr 4, 2022

function Bit (size) {
    this.tree = new Array(size + 1).fill(0)
};

Bit.prototype.lowbit = function (x) {
    return x & -x
}

Bit.prototype.add = function (index, num) {
    while (index && index < this.tree.length) {
        this.tree[index] += num
        index += this.lowbit(index)
    }
}

Bit.prototype.query = function (num) {
    let ans = 0
    while (num) {
        ans += this.tree[num]
        num -= this.lowbit(num)
    }
    return ans
}

image

https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self/solution/shu-zhuang-shu-zu-de-xiang-xi-fen-xi-by-yangbingji/

@HelKyle
Copy link
Author

HelKyle commented May 2, 2022

https://leetcode-cn.com/problems/my-calendar-ii/submissions/
https://leetcode.cn/problems/range-module/submissions/

线段树实现

function Node (start, end) {
    this.val = 0
    this.lazy = 0
    this.start = start
    this.end = end
    this.left = null
    this.right = null
}

function SegmentTree (start, end) {
    this.root = new Node(start, end)
}

SegmentTree.prototype.update = function (start, end) {
    this.updateNode(this.root, start, end)
}

SegmentTree.prototype.updateNode = function(node, start, end) {
    if (!node) {
        return
    }
    if (start > node.end || end < node.start) {
        return
    } else if (start <= node.start && end >= node.end) {
        node.lazy ++
        node.val ++
        return
    } else {
        this.pushdown(node);
        this.updateNode(node.left, start, end);
        this.updateNode(node.right, start, end);
        this.pushup(node);
    }
}

SegmentTree.prototype.pushdown = function (node) {
    if (!node) {
        return
    }
    const mid = Math.floor((node.start + node.end) / 2) 
    if (!node.left) {
        node.left = new Node(node.start, mid)
    }
    if (!node.right) {
        node.right = new Node(mid + 1, node.end)
    }
    node.left.lazy += node.lazy
    node.left.val += node.lazy
    node.right.lazy += node.lazy
    node.right.val += node.lazy
    node.lazy = 0
}

SegmentTree.prototype.pushup = function (node) {
    node.val = Math.max(node.left.val, node.right.val)
}

SegmentTree.prototype.query = function (start, end) {
    return this.queryNode(this.root, start, end)
}

SegmentTree.prototype.queryNode = function (node, start, end) {
    if (!node) {
        return 0;
    }
    if (start > node.end || end < node.start) {
        return 0;
    } else if (start <= node.start && end >= node.end) {
        return node.val;
    } else {
        this.pushdown(node);
        return Math.max(this.queryNode(node.left, start, end), this.queryNode(node.right, start, end));
    }
}

@HelKyle
Copy link
Author

HelKyle commented Jun 30, 2022

const isPrime = (n) => {
    if (n === 1) {
        return false;
    }
    for (let i = 2; i * i <= n; i++) {
        if (n % i === 0) {
            return false;
        }
    }
    return true;
}

@HelKyle
Copy link
Author

HelKyle commented Nov 12, 2022

class Heap {
  constructor (compare = (a, b) => a - b) {
    this.compare = compare
    this.list = []
  }

  get size () {
    return this.list.length
  }

  get top () {
    return this.list[0]
  }

  left (index) {
    return index * 2 + 1
  }

  right (index) {
    return index * 2 + 2
  }

  parent (index) {
    return (index - 1) >> 1
  }

  swap (index1, index2) {
    [this.list[index1], this.list[index2]] = [this.list[index2], this.list[index1]]
  }

  heapify (index) {
    const leftIndex = this.left(index)
    const rightIndex = this.right(index)
    let cur = index

    if (this.list[leftIndex] !== undefined && this.compare(this.list[cur], this.list[leftIndex]) > 0) {
      cur = leftIndex
    }
    if (this.list[rightIndex] !== undefined && this.compare(this.list[cur], this.list[rightIndex]) > 0) {
      cur = rightIndex
    } 

    if (cur !== index) {
      this.swap(cur, index)
      this.heapify(cur)
    }
  }

  insert(node) {
    this.list.push(node)
    let cur = this.size - 1
    let parentIndex = this.parent(cur)

    while (cur > 0 && this.compare(this.list[parentIndex], this.list[cur]) > 0) {
      this.swap(cur, parentIndex)
      cur = parentIndex
      parentIndex = this.parent(cur)
    }
  }

  remove() {
    this.swap(0, this.size - 1)
    const result = this.list.pop()
    this.heapify(0)
    return result
  }
}

@HelKyle
Copy link
Author

HelKyle commented Dec 24, 2022

计算 n 内不能被 divisor 整除的正整数有多少个:

Math.floor(n / divisor) * (divisor - 1) + (n % divisor)

@HelKyle
Copy link
Author

HelKyle commented Jan 1, 2023

找出一个前面的质数

const max = 1e6 + 33
const primes = []
const is_primes = new Array(max).fill(1)
for (let i = 2; i < max; i ++) {
    if (is_primes[i] === 1) {
        primes.push(i)
        for (let j = i * i; j < max; j += i) {
            is_primes[j] = 0
        }
    }
}

@HelKyle
Copy link
Author

HelKyle commented Jan 1, 2023

计算所有质因子

function getPrimeFactor(num) {
    res = []
    for (let i = 2; i < Math.sqrt(num) + 1; i ++) {
        let cnt = 0
        while ((num % i) === 0) {
            num /= i
            cnt += 1
        }
        if (cnt) {
            res.push([i, cnt])
        }
        if (i > num) {
            break
        }
    }
    if (num !== 1 || res.length === 0) {
        res.push([num, 1])
    }
    return res
}

@HelKyle
Copy link
Author

HelKyle commented Apr 30, 2023

矩阵遍历

const dirs = [
      [-1, 0],
      [0, -1],
      [1, 0],
      [0, 1]
  ]
  const visited = new Array(grid.length).fill(0)
      .map(() => new Array(grid[0].length).fill(0))
  let ans = 0
  
  function dfs (i, j) {
      if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length) {
          return 0
      }
      if (grid[i][j] === 0 || visited[i][j]) {
          return 0
      }
      visited[i][j] = 1
      let cur = grid[i][j]
      for (const [di, dj] of dirs) {
          cur += dfs(i + di, j + dj, cur)
      }
      return cur
  }
  
  for (let i = 0; i < grid.length; i ++) {
      for (let j = 0; j < grid[0].length; j ++) {
          if (!visited[i][j]) {
              ans = Math.max(ans, dfs(i, j))
          }
      }
  }
  return ans

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment