资讯专栏INFORMATION COLUMN

FE-ES 前端数据结构与算法leedcode训练合集40题

dabai / 1787人阅读

摘要:无关知识点精通一个领域切碎知识点刻意练习反馈切题四件套审题所有解法比较时间空间复杂度加强编码测试用例数组,链表数组查询插入删除链表查询插入删除翻转链表两两翻转链表判断链表是否有环栈,队列判断合法括号栈模拟队列队列模拟栈找第大的元素

无关知识点

1.精通一个领域:

切碎知识点

刻意练习

反馈

2.切题四件套

审题

所有解法

比较(时间/空间复杂度)

加强

编码

测试用例

http://www.bigocheatsheet.com/

数组,链表

数组 查询:O(1)插入 O(n) 删除O(n)
链表 查询:O(n)插入 O(1) 删除O(1)

206.翻转链表 reverse-linked-list

</>复制代码

  1. /**
  2. * @param {ListNode} head
  3. * @return {ListNode}
  4. */
  5. var reverseList = function(head) {
  6. var [prev,curr]=[null,head]
  7. while(curr){
  8. [curr.next,curr,prev]=[prev,curr.next,curr]
  9. }
  10. return prev
  11. };
24. 两两翻转链表 Swap Nodes in Pairs

</>复制代码

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val) {
  4. * this.val = val;
  5. * this.next = null;
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {ListNode}
  11. */
  12. var swapPairs = function(head) {
  13. if(!head||!head.next)return head
  14. var c,a=head,$head=b=head.next
  15. while(a&&b){
  16. c=b.next
  17. a.next=(c&&c.next)||c
  18. b.next=a
  19. a=c
  20. b=a&&a.next
  21. }
  22. return $head
  23. };
141.判断链表是否有环 Linked List Cycle

</>复制代码

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val) {
  4. * this.val = val;
  5. * this.next = null;
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {boolean}
  11. */
  12. var hasCycle = function(head) {
  13. if (!head || !head.next) return false
  14. var slow = head,fast = head.next
  15. while(fast.next && fast.next.next) {
  16. slow = slow.next
  17. fast = fast.next.next
  18. if (slow == fast) return true
  19. }
  20. return false
  21. };
栈,队列 20. 判断合法括号 Valid Parentheses

</>复制代码

  1. /**
  2. * @param {string} s
  3. * @return {boolean}
  4. */
  5. var isValid = function(s) {
  6. var arr=[],s=s.split(""),t
  7. while(t=s.shift())
  8. if(["{","[","("].includes(t))
  9. arr.push(t)
  10. else if(!["[]","()","{}"].includes(arr.pop()+t))
  11. return false
  12. return arr.length==0
  13. };
232. 栈模拟队列 Implement Queue using Stacks

</>复制代码

  1. class MyQueue{
  2. constructor(){
  3. this.stackIn=[]
  4. this.stackOut=[]
  5. }
  6. push(x){
  7. this.stackIn.push(x)
  8. }
  9. pop(){
  10. var t,$r
  11. while(t=this.stackIn.pop())this.stackOut.push(t)
  12. $r=this.stackOut.pop()
  13. while(t=this.stackOut.pop())this.stackIn.push(t)
  14. return $r
  15. }
  16. peek() {
  17. var t,$r
  18. while(t=this.stackIn.pop())this.stackOut.push(t)
  19. $r=this.stackOut.pop()
  20. this.stackOut.push($r)
  21. while(t=this.stackOut.pop())this.stackIn.push(t)
  22. return $r
  23. }
  24. empty() {
  25. return this.stackIn.length==0
  26. }
  27. }
225. 队列模拟栈 Implement Stack using Queues

</>复制代码

  1. class MyStack {
  2. constructor(){
  3. this.qIn=[]
  4. this.qOut=[]
  5. }
  6. push(x){this.qIn.push(x)}
  7. pop() {
  8. var t
  9. while(this.qIn.length>1){
  10. t=this.qIn.shift()
  11. this.qOut.push(t)
  12. }
  13. var $r=this.qIn.shift()
  14. while(this.qOut.length){
  15. t=this.qOut.shift()
  16. this.qIn.push(t)
  17. }
  18. return $r
  19. }
  20. top() {
  21. var t
  22. while(this.qIn.length>1){
  23. t=this.qIn.shift()
  24. this.qOut.push(t)
  25. }
  26. var $r=this.qIn.shift()
  27. this.qOut.push($r)
  28. while(this.qOut.length){
  29. t=this.qOut.shift()
  30. this.qIn.push(t)
  31. }
  32. return $r
  33. }
  34. empty() {return this.qIn.length===0}
  35. }
703. 找第K大的元素 Kth Largest Element in a Stream

</>复制代码

  1. class tree{
  2. constructor(data,k){this.data=data;this.size=k}
  3. n(i,v){
  4. if(v!==undefined)this.data[i]=v;return;
  5. return {
  6. $i:i, $l:2*i+1, $r:2*i+2,
  7. v:this.data[i], l:this.data[2*i+1], r:this.data[2*i+2]}
  8. }
  9. add(v){
  10. if(this.data.lengththis.min()){
  11. this.n(0,v)
  12. this.sort(0)
  13. }
  14. }
  15. min(){return this.data[0]!==undefined?this.data[0]:null}
  16. max(){
  17. var i=0,n,max;
  18. while(i=n.r)?n.$l:n.$r
  19. }
  20. return max
  21. }
  22. minHeap(){
  23. var i=parseInt(this.data.length/2)
  24. for(;i>=0;i--)this.sort(i)
  25. }
  26. sort(i){
  27. var n=this.n(i)
  28. if(n.l===undefined)return
  29. var min=Math.min(n.v,n.l,n.r!==undefined?n.r:Infinity)
  30. switch(min){
  31. case n.l:
  32. this.n(n.$i,n.l);this.n(n.$l,n.v);this.sort(n.$l);break;
  33. case n.r:
  34. this.n(n.$i,n.r);this.n(n.$r,n.v);this.sort(n.$r);break;
  35. }
  36. }
  37. }
  38. /**
  39. * @param {number} k
  40. * @param {number[]} nums
  41. */
  42. var KthLargest = function(k, nums) {
  43. this.tree=new tree(nums.splice(0,k),k)
  44. this.tree.minHeap()
  45. while(nums.length)
  46. this.tree.add(nums.pop())
  47. }
  48. KthLargest.prototype.add = function(val) {
  49. this.tree.add(val)
  50. return this.tree.min()
  51. };
239. 滑动窗口最大值 Sliding Window Maximum

</>复制代码

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} k
  4. * @return {number[]}
  5. */
  6. var maxSlidingWindow = function(nums, k) {
  7. if(!nums.length){return nums}
  8. var tmp=nums.slice(0,k), res=[nums[$max]],
  9. $max=tmp.lastIndexOf(Math.max(...tmp)),
  10. $left=1, $right=k
  11. for(;$right=nums[$max])
  12. $max=$right
  13. else if($max===$left-1){
  14. tmp=nums.slice($left,$right+1)
  15. $max=$left+tmp.lastIndexOf(Math.max(...tmp))
  16. }
  17. res.push(nums[$max])
  18. }
  19. return res
  20. };
Map Set 哈希表 1. 两数之和 Two Sum

</>复制代码

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} target
  4. * @return {number[]}
  5. */
  6. var twoSum = function(nums, target) {
  7. let res = {}
  8. for (let i=0; i
  9. 15. 三数之和 3Sum
  10. </>复制代码

    1. /**
    2. * @param {number[]} nums
    3. * @return {number[][]}
    4. */
    5. var threeSum = function(nums) {
    6. var result = []
    7. nums.sort((a, b)=>a - b)
    8. var end, middle, sum, tripplet, set = new Set()
    9. for (var start = 0; start < nums.length - 2; start++) {
    10. if (start > 0 && nums[start] == nums[start-1])continue
    11. end = nums.length - 1
    12. middle = start + 1
    13. while (middle < end) {
    14. sum = nums[start] + nums[middle] + nums[end]
    15. if (sum === 0) {
    16. tripplet = [nums[start], nums[middle], nums[end]];
    17. trippletKey = nums[start]+ ":" +nums[middle]+ ":" +nums[end]
    18. if (!set.has(trippletKey)) {
    19. set.add(trippletKey)
    20. result.push(tripplet)
    21. }
    22. while (middle < end && nums[middle] === nums[middle+1])middle++
    23. while (middle < end && nums[end] === nums[end-1])end--
    24. middle++
    25. end--
    26. }
    27. else (sum > 0) ? end-- : middle++
    28. }
    29. }
    30. return result
    31. };
  11. 18. 四数之和 4Sum
  12. </>复制代码

    1. /**
    2. * @param {number[]} nums
    3. * @param {number} target
    4. * @return {number[][]}
    5. */
    6. var fourSum = function(nums, target) {
    7. const result = [];
    8. nums.sort((a, b) => a - b);
    9. for (let i=0; i 0 && nums[i] === nums[i-1])continue
    10. for (let j=i+1; j i + 1 && nums[j] === nums[j-1])continue
    11. if (nums[i] + nums[j] + nums[j+1] + nums[j+2] > target)break
    12. if (nums[i] + nums[j] + nums[nums.length-2] + nums[nums.length-1] < target)continue
    13. let left = j + 1, right = nums.length - 1
    14. while (left < right) {
    15. const sum = nums[i] + nums[j] + nums[left] + nums[right]
    16. if (sum === target) {
    17. result.push([ nums[i], nums[j], nums[left], nums[right] ])
    18. while (nums[left] === nums[left+1] && left < right)left++
    19. while (nums[right] === nums[right-1] && left < right)right--
    20. left++
    21. right--
    22. }
    23. else if (sum < target) left++
    24. else right--
    25. }
    26. }
    27. }
    28. return result
    29. }
  13. 98. 验证二叉搜索树 Validate Binary Search Tree
  14. </>复制代码

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val) {
    4. * this.val = val;
    5. * this.left = this.right = null;
    6. * }
    7. */
    8. /**
    9. * @param {TreeNode} root
    10. * @return {boolean}
    11. */
    12. var isEmpty=(node)=>node===null||node.val===null
    13. var isValidBST = (root) =>isEmpty(root)?true:(bst(root))[0]
    14. function bst(node){
    15. var l,r,lmin,lmax,rmin,rmax
    16. if(isEmpty(node.right)&&!isEmpty(node.left)){
    17. [l,lmin,lmax]=bst(node.left)
    18. return [l&&lmaxnode.val,node.val,rmax]
    19. }
    20. else if((!isEmpty(node.left))&&(!isEmpty(node.right))){
    21. [l,lmin,lmax]=bst(node.left)
    22. [r,rmin,rmax]=bst(node.right)
    23. return [l&&r&&lmaxnode.val,lmin,rmax]
    24. }
    25. else return [true,node.val,node.val]
    26. }
  15. 235. 二叉搜索树最近公共祖先 Lowest Common Ancestor of a Binary Search Tree
  16. </>复制代码

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val) {
    4. * this.val = val;
    5. * this.left = this.right = null;
    6. * }
    7. */
    8. /**
    9. * @param {TreeNode} root
    10. * @param {TreeNode} p
    11. * @param {TreeNode} q
    12. * @return {TreeNode}
    13. */
    14. var lowestCommonAncestor = function(root, p, q) {
    15. if(root===null||root===p||root===q)return root
    16. var l=lowestCommonAncestor(root.left,p,q)
    17. var r=lowestCommonAncestor(root.right,p,q)
    18. return l&&r&&root||l||r
    19. };
  17. 236. 二叉树最近公共祖先 Lowest Common Ancestor of a Binary Tree
  18. </>复制代码

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val) {
    4. * this.val = val;
    5. * this.left = this.right = null;
    6. * }
    7. */
    8. /**
    9. * @param {TreeNode} root
    10. * @param {TreeNode} p
    11. * @param {TreeNode} q
    12. * @return {TreeNode}
    13. */
    14. var empty=node=>node===null||node.val===null
    15. var lowestCommonAncestor = function(root, p, q) {
    16. var l,r
    17. if(empty(root)||root===p||root===q)return root
    18. l=lowestCommonAncestor(root.left,p,q)
    19. r=lowestCommonAncestor(root.right,p,q)
    20. return l&&r&&root||l||r
    21. }
  19. 二叉树遍历&递归分治
  20. 递归四步
  21. </>复制代码

    1. function recursion(level,data){
    2. //recursion termonator
    3. if level>MAX_LEVEL
    4. return result
    5. //process logic in current level
    6. process_data(level,data)
    7. //drill down
    8. recursion(level+1,data1)
    9. //reverse the current level
    10. reverse_state(level)
    11. }
  22. DFS
  23. </>复制代码

    1. visited=set()
    2. def dfs(node,visited):
    3. visited.add(node)
    4. #...
    5. for next_node in node.children():
    6. if not next_ndoe in visited:
    7. dfs(next_node,visited)
  24. BFS
  25. </>复制代码

    1. def BFS(graph,start,end)
    2. queue=[]
    3. queue.append([start])
    4. visited.add(start)
    5. while queue:
    6. node=queue.pop()
    7. visited.add(node)
    8. process(node)
    9. nodes=genertate_related_nodes(node)
    10. queue.push(nodes)
  26. 二分查找
  27. </>复制代码

    1. let,right=0,len(array)-1
    2. while left<=right:
    3. mid=left+(right-left)/2
    4. if array[mid]==target:
    5. #find the target!!
    6. break or return result
    7. elif array[mid]
    8. 50. 次方 Pow(x, n)
    9. </>复制代码

      1. /**
      2. * @param {number} x
      3. * @param {number} n
      4. * @return {number}
      5. */
      6. var myPow = function(x, n) {
      7. if(!n)return 1
      8. if(n<0)return 1/myPow(x,-n)
      9. if(n%2)return x*myPow(x,n-1)
      10. return myPow(x*x,n/2)
      11. };
    10. </>复制代码

      1. var myPow = function(x, n) {
      2. if(n<0){
      3. x=1/x
      4. n=-n
      5. }
      6. var pow=1
      7. while(n){
      8. if(n&1)pow*=x
      9. x*=x
      10. n=parseInt(n/2)
      11. }
      12. return pow
      13. };
    11. 169. 求众数 Majority Element
    12. </>复制代码

      1. /**
      2. * @param {number[]} nums
      3. * @return {number}
      4. */
      5. var majorityElement = function(nums) {
      6. let major = nums[0],count = 1
      7. for (let i = 1; i < nums.length; i++) {
      8. if (major === nums[i]) count++
      9. else count--
      10. if (count === 0) {
      11. major = nums[i]
      12. count = 1
      13. }
      14. }
      15. return major
      16. };
    13. 102. 二叉树层次遍历 Binary Tree Level Order Traversal
    14. </>复制代码

      1. /**
      2. * Definition for a binary tree node.
      3. * function TreeNode(val) {
      4. * this.val = val;
      5. * this.left = this.right = null;
      6. * }
      7. */
      8. /**
      9. * @param {TreeNode} root
      10. * @return {number[][]}
      11. */
      12. var levelOrder = function(root) {
      13. if(isEmpty(root))return []
      14. var h=0,isEnd=false,ans=[[root.val]]
      15. print(root,h,ans)
      16. return ans
      17. };
      18. var isEmpty=root=>root===null||root.val===null
      19. function print(root,h,ans){
      20. h++
      21. if(!isEmpty(root.left)){
      22. ans[h]=ans[h]||[],ans[h].push(root.left.val)
      23. print(root.left,h,ans)
      24. }
      25. if(!isEmpty(root.right)){
      26. ans[h]=ans[h]||[],ans[h].push(root.right.val)
      27. print(root.right,h,ans)
      28. }
      29. }
    15. </>复制代码

      1. var levelOrder = function(root) {
      2. if (!root) return []
      3. const queue = [[root,0]]
      4. const result = []
      5. while (queue.length !== 0) {
      6. const [node, level] = queue.shift()
      7. if (level >= result.length) result.push([])
      8. result[level].push(node.val)
      9. if (node.left){
      10. const left = [node.left,level + 1]
      11. queue.push(left)}
      12. if (node.right){
      13. const right = [node.right,level + 1]
      14. queue.push(right)}
      15. }
      16. return result
      17. }
    16. 104. 二叉树最大深度 Maximum Depth of Binary Tree
    17. </>复制代码

      1. /**
      2. * Definition for a binary tree node.
      3. * function TreeNode(val) {
      4. * this.val = val;
      5. * this.left = this.right = null;
      6. * }
      7. */
      8. /**
      9. * @param {TreeNode} root
      10. * @return {number}
      11. */
      12. var maxDepth = function(root,h=0) {
      13. if(!root)return h
      14. h++
      15. return Math.max(maxDepth(root.left,h),maxDepth(root.right,h))
      16. };
    18. </>复制代码

      1. var maxDepth = function(root,h=0) {
      2. var h=0,nodes=[[null,0]]
      3. while(root&&root.val){
      4. h++
      5. if(root.right) nodes.push([root.right,h+1])
      6. if(root.left){
      7. root=root.left
      8. h++
      9. }
      10. else [root,h]=nodes.pop()
      11. }
      12. return h
      13. };
    19. 111. 二叉树最小深度 Minimum Depth of Binary Tree
    20. </>复制代码

      1. /**
      2. * Definition for a binary tree node.
      3. * function TreeNode(val) {
      4. * this.val = val;
      5. * this.left = this.right = null;
      6. * }
      7. */
      8. /**
      9. * @param {TreeNode} root
      10. * @return {number}
      11. */
      12. var minDepth = function(root) {
      13. if(root===null)return 0
      14. if(root.right===null){
      15. return minDepth(root.left)+1
      16. }
      17. if(root.left==null){
      18. return minDepth(root.right)+1
      19. }
      20. return Math.min(minDepth(root.left),minDepth(root.right))+1
      21. };
    21. </>复制代码

      1. const currentNode = (node, depth) => ({node,depth})
      2. var minDepth = function(root){
      3. if(root === null)return 0
      4. const q = []
      5. q.push(currentNode(root, 1))
      6. while(q.length){
      7. let { node, depth } = q.shift()
      8. if(!node.left && !node.right) return depth
      9. else {
      10. node.left && q.push(currentNode(node.left, depth + 1))
      11. node.right && q.push(currentNode(node.right, depth + 1))
      12. }
      13. }
      14. }
    22. 剪枝
    23. 22. 生成括号 Generate Parentheses
    24. </>复制代码

      1. var generateParenthesis = function(n) {
      2. if(n===1)return ["()"]
      3. var l=1,r=0,ans=[],str="("
      4. get(str,"(",l,r,n,ans)
      5. get(str,")",l,r,n,ans)
      6. return ans
      7. }
      8. function get(str,char,l,r,n,ans){
      9. if(char===")"&&l===r)return
      10. str+=char
      11. if(char==="(")l++
      12. else r++
      13. if(l===n){
      14. while(r
      15. 51.N皇后 N-Queens
      16. </>复制代码

        1. /**
        2. * @param {number} n
        3. * @return {string[][]}
        4. */
        5. var solveNQueens = function(n) {
        6. var result=[]
        7. function DFS(lie,pie,na){
        8. var p=lie.length
        9. if(p===n){result.push(lie);return}
        10. for(var q=0;qo.map(v=>{
        11. var s=".".repeat(n).split("")
        12. s[v]="Q"
        13. return s.join("")
        14. }))
        15. }
      17. 52. N皇后II N-Queens II
      18. </>复制代码

        1. /**
        2. * @param {number} n
        3. * @return {number}
        4. */
        5. var totalNQueens = function(n) {
        6. var result=0
        7. function DFS(lie,pie,na){
        8. var p=lie.length
        9. if(p===n){result++;return}
        10. for(var q=0;q
        11. 37. 数独 Sudoku Solver
        12. </>复制代码

          1. /**
          2. * @param {character[][]} board
          3. * @return {void} Do not return anything, modify board in-place instead.
          4. */
          5. var solveSudoku = function(board) {
          6. if(board===null||board.length===0)return
          7. return solve(board)
          8. }
          9. function solve(board){
          10. for(var i=0;i<9;i++){
          11. for(var j=0;j<9;j++){
          12. if(board[i][j]=="."){
          13. for(var c=1;c<=9;c++){
          14. if(isValid(board,i,j,c)){
          15. board[i][j]=""+c
          16. if(solve(board))return true
          17. else board[i][j]="."
          18. }
          19. }
          20. return false
          21. }
          22. }
          23. }
          24. return board
          25. }
          26. function isValid(board,row,col,c){
          27. var _col=parseInt(col/3)
          28. var _row=parseInt(row/3)
          29. for(var i=0;i<9;i++){
          30. var _i=parseInt(i/3)
          31. if( [board[i][col],
          32. board[row][i],
          33. board[3*_row+_i][3*_col+i%3]
          34. ].some(v=>v!="."&&v==c))return false
          35. }
          36. return true
          37. }
        13. 208. 字典树 Implement Trie (Prefix Tree)
        14. </>复制代码

          1. var Trie = function() {
          2. this.root={}
          3. };
          4. Trie.prototype.insert = function(word) {
          5. var node=this.root
          6. for(var c of word){
          7. if(!(c in node))
          8. node[c]={}
          9. node=node[c]
          10. }
          11. node["$"]=true
          12. };
          13. Trie.prototype.search = function(word) {
          14. var node=this.root
          15. for(var c of word)
          16. if(c in node) node=node[c]
          17. else return false
          18. return node["$"]===true
          19. };
          20. Trie.prototype.startsWith = function(prefix) {
          21. var node=this.root
          22. for(var c of prefix)
          23. if(c in node) node=node[c]
          24. else return false
          25. return true
          26. };
        15. 212. 单词搜索 Word Search II
        16. </>复制代码

          1. /**
          2. * @param {character[][]} board
          3. * @param {string[]} words
          4. * @return {string[]}
          5. */
          6. var findWords = function(board, words) {
          7. var tree=new Trie()
          8. global.ans=new Set()
          9. words.forEach(v=>{tree.insert(v)})
          10. for(var i=0;i{
          11. if(v[0]<0||v[0]>=board.length||v[1]<0||v[1]>=board[0].length)return
          12. var index=v.join(",")
          13. if(!last.has(index)){
          14. check(board,v[0],v[1],node,new Set(last))
          15. }
          16. })
          17. }
        17. 位运算
        18. 概要
        19. X&1==1 or 0 判断奇偶

        20. X=X&(X-1) 清零最低位的1

        21. X&-X 得到最低位的1

        22. 191. 1的个数 Number of 1 Bits
        23. </>复制代码

          1. /**
          2. * @param {number} n - a positive integer
          3. * @return {number}
          4. */
          5. var hammingWeight = function(n) {
          6. var count=0
          7. while(n){
          8. n=n&(n-1)
          9. count++
          10. }
          11. return count
          12. };
        24. 231.二的次方 Power of Two
        25. </>复制代码

          1. /**
          2. * @param {number} n
          3. * @return {boolean}
          4. */
          5. var isPowerOfTwo = (n)=>n > 0 && !(n & (n - 1))
        26. 52.N皇后位运算 N-Queens II
        27. </>复制代码

          1. /**
          2. * @param {number} n
          3. * @return {number}
          4. */
          5. var totalNQueens = function(n) {
          6. var result=0
          7. function DFS(hang,lie,pie,na){
          8. if(hang>=n){result++;return}
          9. var bits=(~(lie|pie|na))&((1<0){
          10. var p=bits&-bits
          11. DFS(hang+1,lie|p,(pie|p)<<1,(na|p)>>1)
          12. bits&=bits-1
          13. }
          14. }
          15. DFS(0,0,0,0)
          16. return result
          17. }
        28. 动态规划
        29. 模板
        30. </>复制代码

          1. dp=new init [m+1][n+1]
          2. dp[0][0]=x
          3. dp[0][28]=y
          4. for i=0;i<=n;++i
          5. for j=0;j<=m;++j
          6. #...
          7. dp[i][j]=min(dp[i-1][j],dp[i][j-1])
          8. return dp[m][n]
        31. 70. 爬楼梯 Climbing Stairs
        32. </>复制代码

          1. /**
          2. * @param {number} n
          3. * @return {number}
          4. */
          5. var climbStairs = function(n) {
          6. dp=[0,1,2]
          7. for(var i=3;i<=n;i++){
          8. dp[i]=dp[i-1]+dp[i-2]
          9. }
          10. return dp[n]
          11. };
        33. 120. 三角形最小路径和 Triangle
        34. </>复制代码

          1. /**
          2. * @param {number[][]} triangle
          3. * @return {number}
          4. */
          5. var minimumTotal = function(triangle) {
          6. var dp=[[+triangle[0][0]]]
          7. var i,j
          8. for(i=1;i0?(+dp[i-1][j-1]+triangle[i][j]):Infinity
          9. var r=(j
          10. 152. 乘积最大子序列 Maximum Product Subarray
          11. </>复制代码

            1. /**
            2. * @param {number[]} nums
            3. * @return {number}
            4. */
            5. var maxProduct = function(nums) {
            6. var i,dp=[{min:nums[0],max:nums[0]}],ans=nums[0]
            7. for(i=1;i
            8. 188. 股票交易最优决策 Best Time to Buy and Sell Stock IV
            9. </>复制代码

              1. var maxProfit = function(K, prices) {
              2. var D=prices.length,mp=[],k,i
              3. max=-Infinity,min=prices[0]
              4. if(!D||!K)return 0
              5. if(K>=D/2){
              6. max=0
              7. for(i = 1; i < prices.length; i++)
              8. if(prices[i] > prices[i-1])
              9. max += (prices[i] - prices[i-1])
              10. return max
              11. }
              12. for(i=0;i
              13. </>复制代码

                1. /**
                2. * @param {number} k
                3. * @param {number[]} prices
                4. * @return {number}
                5. */
                6. var maxProfit = function(k, prices) {
                7. var n=prices.length
                8. var k = Math.min(k,n)
                9. if (!k)return 0
                10. if(k>=n/2){
                11. let max=0
                12. for(i = 1; i < n; i++)
                13. if(prices[i] > prices[i-1])
                14. max += (prices[i] - prices[i-1])
                15. return max
                16. }
                17. let dp = Array(n).fill(0)
                18. while (k) {
                19. dp[0] = -prices[0]
                20. for (let i = 1; i < n; i++)
                21. dp[i] = Math.max(dp[i - 1], dp[i] - prices[i])
                22. dp[0] = 0
                23. for (let i = 1; i < n; i++)
                24. dp[i] = Math.max(dp[i - 1], prices[i] + dp[i])
                25. k--
                26. }
                27. return dp.pop()
                28. };
              14. 300.最大上升子序列 Longest Increasing Subsequence
              15. </>复制代码

                1. /**
                2. * @param {number[]} nums
                3. * @return {number}
                4. */
                5. var lengthOfLIS = function(nums) {
                6. if(!nums||!nums.length)return 0
                7. var res=1
                8. var dp=new Array(nums.length-1)
                9. for(var i=0;i
                10. 322.零钱兑换 Coin Change
                11. </>复制代码

                  1. /**
                  2. * @param {number[]} coins
                  3. * @param {number} amount
                  4. * @return {number}
                  5. */
                  6. var coinChange = function(coins, amount) {
                  7. var i,j,dp=[0]
                  8. if(amount===0)return 0
                  9. for(var i=1;i<=amount;i++){
                  10. var res=[]
                  11. for(var j=0;j0)
                  12. dp[i]=Math.min(...res)+1
                  13. }
                  14. return dp[amount]||-1
                  15. };
                12. 72. 编辑距离 Edit Distance
                13. </>复制代码

                  1. /**
                  2. * @param {string} word1
                  3. * @param {string} word2
                  4. * @return {number}
                  5. */
                  6. var minDistance = function(word1, word2) {
                  7. if(!word1.length)return word2.length
                  8. if(!word2.length)return word1.length
                  9. var dp=Array.from(Array(word1.length+1), () =>
                  10. Array(word2.length+1).fill(0))
                  11. for(i of Array(word1.length+1).keys())
                  12. dp[i][0]=i
                  13. for(j of Array(word2.length+1).keys())
                  14. dp[0][j]=j
                  15. for(var i=1;i<=word1.length;i++)
                  16. for(var j=1;j<=word2.length;j++)
                  17. dp[i][j]=Math.min(dp[i-1][j]+1,
                  18. dp[i][j-1]+1,
                  19. dp[i-1][j-1]+(word1[i-1]===word2[j-1]?0:1))
                  20. return dp.pop().pop()
                  21. };
                14. 并查集
                15. 200 岛屿个数 Number of Islands
                16. </>复制代码

                  1. /**
                  2. * @param {character[][]} grid
                  3. * @return {number}
                  4. */
                  5. var numIslands = function(grid) {
                  6. let count = 0,
                  7. h = grid.length,
                  8. w = h && grid[0].length
                  9. for(let i of Array(h).keys())
                  10. for(let j of Array(w).keys()){
                  11. if(grid[i][j] === "0") continue
                  12. count ++
                  13. dfs(i, j)
                  14. }
                  15. return count
                  16. function dfs(n, m){
                  17. if(n < 0 || m < 0 || n >= h || m >= w) return;
                  18. if(grid[n][m] === "1"){
                  19. grid[n][m] = "0";
                  20. dfs(n + 1, m);
                  21. dfs(n - 1, m);
                  22. dfs(n, m + 1);
                  23. dfs(n, m - 1);
                  24. }
                  25. }
                  26. }
                17. </>复制代码

                  1. class UnionFind{
                  2. constructor(grid){
                  3. let [m,n]=[grid.length,grid[0].length]
                  4. this.count=0
                  5. this.parent=Array(m*n).fill(-1)
                  6. this.rank=Array(m*n).fill(0)
                  7. for(let i of Array(m).keys())
                  8. for(let j of Array(n).keys())
                  9. if(grid[i][j]=="1"){
                  10. this.parent[i*n+j]=i*n+j
                  11. this.count++
                  12. }
                  13. }
                  14. find(i){
                  15. if (this.parent[i]!=i)
                  16. this.parent[i]=this.find(this.parent[i])
                  17. return this.parent[i]
                  18. }
                  19. union(x,y){
                  20. let rootx=this.find(x)
                  21. let rooty=this.find(y)
                  22. if(rootx!=rooty){
                  23. if(this.rank[rootx]>this.rank[rooty])
                  24. this.parent[rooty]=rootx
                  25. else if(this.rank[rootx]{
                  26. let [nr,nc]=[i+d[0],j+d[1]]
                  27. if(nr>=0&&nc>=0&&nr
                  28. 547. 朋友圈 Friend Circles
                  29. </>复制代码

                    1. /**
                    2. * @param {number[][]} M
                    3. * @return {number}
                    4. */
                    5. var findCircleNum=function(M){
                    6. const n = M.length
                    7. const roots = Array.from(Array(n).keys())
                    8. for (let i = 0; i < n; i++)
                    9. for (let j = i+1; j < n; j++)
                    10. if (M[i][j] === 1) {
                    11. const [x, y] = [find(i), find(j)]
                    12. if (x !== y) roots[y] = x
                    13. }
                    14. let result = new Set()
                    15. for (let i = 0; i < roots.length; i++) result.add(find(roots[i]))
                    16. return result.size
                    17. function find(x) {
                    18. while(roots[x] !== x) x = roots[x]
                    19. return x
                    20. }
                    21. }
                  30. 146.最近最少使用缓存 LRU Cache
                  31. </>复制代码

                    1. class LRUCache {
                    2. constructor(capacity) {
                    3. this.capacity = capacity;
                    4. this.map = new Map();
                    5. }
                    6. get(key) {
                    7. let val = this.map.get(key);
                    8. if (typeof val === "undefined") { return -1 }
                    9. this.map.delete(key);
                    10. this.map.set(key, val);
                    11. return val;
                    12. }
                    13. put(key, value) {
                    14. if (this.map.has(key)) { this.map.delete(key) }
                    15. this.map.set(key, value);
                    16. let keys = this.map.keys();
                    17. while (this.map.size > this.capacity) { this.map.delete(keys.next().value) }
                    18. }
                    19. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/102815.html

相关文章

  • 你不能错过的前端面试合集

    摘要:收集的一些前端面试题从面试题发现不足,进而查漏补缺,比通过面试更难得及各大互联网公司前端笔试面试题篇及各大互联网公司前端笔试面试题篇面试题个和个经典面试题前端开发面试题如何面试前端工程师很重要个变态题解析如何通过饿了么面试轻 收集的一些前端面试题 从面试题发现不足,进而查漏补缺,比通过面试更难得 1 BAT及各大互联网公司2014前端笔试面试题--Html,Css篇 2 BAT...

    ninefive 评论0 收藏0
  • 你不能错过的前端面试合集

    摘要:收集的一些前端面试题从面试题发现不足,进而查漏补缺,比通过面试更难得及各大互联网公司前端笔试面试题篇及各大互联网公司前端笔试面试题篇面试题个和个经典面试题前端开发面试题如何面试前端工程师很重要个变态题解析如何通过饿了么面试轻 收集的一些前端面试题 从面试题发现不足,进而查漏补缺,比通过面试更难得 1 BAT及各大互联网公司2014前端笔试面试题--Html,Css篇 2 BAT...

    darkbaby123 评论0 收藏0
  • js算法合集(不定期更新)

    摘要:前言本系列总结了在前端面试中可能遇到的若干算法题,不定期更新最近看有同学面试遇到了阶变态跳问题级台阶,每次最多允许跨步,求多少种跨越方式,下面是一个变种问题题目假设有级台阶,每次最多允许跨步,那么有多少种跨越方式思路采用自顶向下的思考方式 前言:本系列总结了在前端面试中可能遇到的若干算法题,不定期更新 最近看有同学面试遇到了n阶变态跳问题(n级台阶,每次最多允许跨n步,求多少种跨越方式...

    william 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<