查看: 5066| 回复: 8
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] 分享一些用JavaScript刷题的Tips

   
全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
论坛里关于用 JavaScript 刷题的帖子比较少,我想和大家分享一下我总结的一些常用语句以及模板。JavaScript 或者说 NodeJs,被越来越多的运用在后端中。如果你平常使用最多的语言是 JavaScript,那直接用它来刷题找工作没有问题。JavaScript 做起题来的代码量是相对比较少的,一方面是由于本身是一个 dynamically typed 的语言,另一方面是它支持很多简洁的语法。

先贴一下LeetCode Rating。总共参加了103场,都是用JS写的。



Tips:
(建议把以下代码复制到VSCode或者其它editor里面,并保存成.md文件使用。或者是直接下载附件。)
  1. #### 1 Array

  2. ##### 1.1 Array creation

  3. - Create a new array
  4.   `const A = [];`
  5. - Create a subarray
  6.   `const A = B.slice(l, r); // From idx l to r, r is not included`
  7. - Copy from other array
  8.   `const A = [...B];`
  9. - Create an array from a set
  10.   `const A = [...mySet];`
  11. - Create an array from a string
  12.   `const A = [...myStr];`
  13. - Create an array from hashmap keys
  14.   `const A = Object.keys(myMap);`
  15. - Create an array from hashmap values
  16.   `const A = Object.values(myMap);`
  17. - Create an array from hashmap keys and values
  18.   `const A = Object.entries(myMap);`
  19. - Create an array with length `m`
  20.   `const dp = Array(m);`
  21. - Create an array with length `m`, initialized as `0`
  22.   `const dp = Array(m).fill(0);`
  23. - Create a 2-D array with dimension `r x c`, initialized as `-1`
  24.   `const dp = Array.from(Array(r), () => Array(c).fill(-1));`

  25. ##### 1.2 Array modification

  26. - Add an element
  27.   `A.push(x);`
  28. - Add all elements from other array
  29.   `A.push(...B);`
  30. - Add an element from left
  31.   `A.unshift(x);`
  32. - Pop an element
  33.   `A.pop();`
  34. - Pop an element from left
  35.   `A.shift();`
  36. - Remove/add element(s)
  37.   `A.splice(idx, deleteCnt, x); // in place`
  38. - Reverse an array
  39.   `A.reverse(); // in place`
  40. - Sort an array in increasing order
  41.   `A.sort((a, b) => a - b); // in place`
  42. - Other usages
  43.   `A.map(); A.filter(); A.every(); A.some();`

  44. #### 2 String

  45. - Create a string literal
  46.   `const s = "abcd";`
  47. - Create a string from other string
  48.   `const s1 = s2.substring(l, r); // From idx l to r, r is not included`
  49. - Create a string by joining an array
  50.   `const s = A.join("");`
  51. - Create a string of repeating char
  52.   `const s = "xyz".repeat(5);`
  53. - Reverse a string
  54.   `const s1 = [...s2].reverse().join("");`
  55. - Loop a string
  56.   `for (const char of s) {}`
  57. - Split a string
  58.   `const arr = s.split(" ");`

  59. #### 3 Set

  60. - Create a new set
  61.   `const seen = new Set();`
  62. - Create a set from an array
  63.   `const seen = new Set(A);`
  64. - Add an element
  65.   `seen.add(x);`
  66. - Delete an element
  67.   `seen.delete(x);`

  68. #### 4 Hashtable (object)

  69. - Create a new hashtable
  70.   `const g = {};`
  71. - Add a key value pair
  72.   `g[a] = b;`
  73. - Delete a key
  74.   `delete g[a];`
  75. - Detect key exists
  76.   `if (key in g) {}`
  77.   `if (g[key]) {} // Only works if you know there is no falsy value`
  78.   `if (g[key] !== undefined) {}`
  79. - Loop through key value pair
  80.   `for (const [key, value] of Object.entries(g)) {}`

  81. #### 5 Heap

  82. - Create a min heap
  83.   `const minHeap = new Heap((a, b) => a - b);`
  84. - Create a max heap
  85.   `const maxHeap = new Heap((a, b) => b - a);`
  86. - Create a custom heap
  87.   `const heap = new Heap((a, b) => a[0] - b[0] ? a[0] - b[0] : a[1] - b[1]);`
  88. - Create a heap from an array
  89.   `minHeap.heapify(A);`
  90. - Add an element
  91.   `minHeap.add(x);`
  92. - Pop an element
  93.   `minHeap.pop();`
  94. - Peek an element
  95.   `minHeap.peek();`
  96. - Delete an element
  97.   `minHeap.delete(x);`
  98. - Heap implementation

  99. ```js
  100. class Heap {
  101.   constructor(comparator) {
  102.     this.arr = [];
  103.     this.comparator = comparator;
  104.   }

  105.   getL() {
  106.     return this.arr.length;
  107.   }

  108.   getPIdx(i) {
  109.     return Math.floor((i - 1) / 2);
  110.   }

  111.   getLIdx(i) {
  112.     return 2 * i + 1;
  113.   }

  114.   getRIdx(i) {
  115.     return 2 * i + 2;
  116.   }

  117.   swap(i, j) {
  118.     [this.arr[i], this.arr[j]] = [this.arr[j], this.arr[i]];
  119.   }

  120.   peek() {
  121.     if (!this.arr.length) return null;
  122.     return this.arr[0];
  123.   }

  124.   pop() {
  125.     if (!this.arr.length) return null;
  126.     if (this.arr.length === 1) return this.arr.pop();
  127.     const res = this.arr[0];
  128.     // Move last item from end to head
  129.     this.arr[0] = this.arr.pop();
  130.     this.heapifyDown();
  131.     return res;
  132.   }

  133.   add(n) {
  134.     this.arr.push(n);
  135.     this.heapifyUp();
  136.   }

  137.   // Default idx is the first idx
  138.   heapifyDown(idx = 0) {
  139.     let p = idx;
  140.     let c;
  141.     // Compare parent with its children and swap with target child if necessary
  142.     // Do it in a loop
  143.     while (this.getLIdx(p) < this.arr.length) {
  144.       // Get target child first
  145.       if (
  146.         this.getRIdx(p) < this.arr.length &&
  147.         this.comparator(this.arr[this.getRIdx(p)], this.arr[this.getLIdx(p)]) <
  148.           0
  149.       )
  150.         c = this.getRIdx(p);
  151.       else c = this.getLIdx(p);
  152.       // Compare with parent, if not valid, break
  153.       if (this.comparator(this.arr[p], this.arr[c]) <= 0) break;
  154.       // Swap
  155.       this.swap(p, c);
  156.       p = c;
  157.     }
  158.   }

  159.   // Default idx is the last idx
  160.   heapifyUp(idx = this.arr.length - 1) {
  161.     let c = idx;
  162.     let p = null;
  163.     // While has parent
  164.     while (c) {
  165.       p = this.getPIdx(c);
  166.       if (this.comparator(this.arr[p], this.arr[c]) <= 0) break;
  167.       // Swap
  168.       this.swap(p, c);
  169.       c = p;
  170.     }
  171.   }

  172.   heapify(A) {
  173.     // Bottom up
  174.     // Heapify down each item
  175.     this.arr = A;
  176.     for (let i = Math.floor(A.length / 2); i >= 0; i--) {
  177.       this.heapifyDown(i);
  178.     }
  179.   }

  180.   delete(n) {
  181.     const idx = this.arr.indexOf(n);
  182.     this.arr[idx] = this.arr[this.arr.length - 1];
  183.     this.arr.pop();
  184.     this.heapifyDown(idx);
  185.   }
  186. }
  187. ```

  188. #### 6 Union find

  189. ```js
  190. class DS {
  191.   constructor(n) {
  192.     this.root = [...Array(n + 1).keys()];
  193.     this.rank = Array(n + 1).fill(0);
  194.   }
  195.   find(i) {
  196.     if (i !== this.root[i]) this.root[i] = this.find(this.root[i]);
  197.     return this.root[i];
  198.   }
  199.   union(i, j) {
  200.     const [root1, root2] = [this.find(i), this.find(j)];
  201.     if (root1 === root2) return false;
  202.     if (this.rank[root1] > this.rank[root2]) this.root[root2] = root1;
  203.     else if (this.rank[root1] < this.rank[root2]) this.root[root1] = root2;
  204.     else {
  205.       this.root[root2] = root1;
  206.       this.rank[root1]++;
  207.     }
  208.     return true;
  209.   }
  210. }
  211. ```

  212. #### 7 Trie

  213. ```js
  214. // Construct a trie from W (W is an array of words)
  215. const trie = {};
  216. W.forEach((w) => {
  217.   let node = trie;
  218.   for (const c of w) {
  219.     if (!node[c]) node[c] = {};
  220.     node = node[c];
  221.   }
  222.   node.end = true;
  223. });
  224. ```

  225. #### 8 Monotonic queue

  226. e.g. 239-sliding-window-maximum

  227. ```js
  228. const maxSlidingWindow = (A, k) => {
  229.   const win = []; // Store idx
  230.   const res = [];
  231.   for (let i = 0; i < A.length; i++) {
  232.     // Need to get max from win[0], so keep an descending queue
  233.     while (win.length && A[win[win.length - 1]] <= A[i]) win.pop();
  234.     win.push(i);
  235.     // Remove first element if it's out of window
  236.     if (win[0] === i - k) win.shift();
  237.     if (i >= k - 1) res.push(A[win[0]]);
  238.   }
  239.   return res;
  240. };
  241. ```

  242. #### 9 Quick sort/select

  243. ```js
  244. const partition = (A, l, r) => {
  245.   let j = l;
  246.   let boundary = A[r];
  247.   for (let i = l; i < r; i++) {
  248.     if (A[i] < boundary) {
  249.       [A[i], A[j]] = [A[j], A[i]];
  250.       j++;
  251.     }
  252.   }
  253.   [A[j], A[r]] = [A[r], A[j]];
  254.   return j;
  255. };

  256. const quickSort = (A, l, r) => {
  257.   if (r <= l) return;
  258.   const idx = partition(A, l, r);
  259.   quickSort(A, l, idx - 1);
  260.   quickSort(A, idx + 1, r);
  261.   return A;
  262. };
  263. ```

  264. #### 10 Bianry index tree

  265. ```js
  266. class BIT {
  267.   constructor(n) {
  268.     this.pre = Array(n + 1).fill(0);
  269.   }

  270.   update(i, delta) {
  271.     while (i < this.pre.length) {
  272.       this.pre[i] += delta;
  273.       i += i & -i;
  274.     }
  275.   }

  276.   getSum(i) {
  277.     let res = 0;
  278.     while (i) {
  279.       res += this.pre[i];
  280.       i -= i & -i;
  281.     }
  282.     return res;
  283.   }
  284. }
  285. ```
复制代码

js_tips.pdf

92.71 KB, 下载次数: 87, 下载积分: 大米 -1 颗

评分

参与人数 10大米 +75 收起 理由
小亩_56g8uvy + 1 赞一个
DiDiRan + 1 很有用的信息!
Klauss + 1 很有用的信息!
admin + 66
wind_sunlight + 1 给你点个赞!

查看全部评分


上一篇:新手或转码刷题怎么刷?
下一篇:新手刷题一些个人总结-大龄转码old yong
推荐
 楼主| zachzwy 2022-4-16 13:59:07 | 只看该作者
全局:
gagawoahlala 发表于 2022-4-15 19:32
楼主,你在面试的时候如果碰到了PQ的题咋办?要现场实现一个heap吗?

面试的时候碰到使用PQ的题,其实是个很好的和面试官交流的机会。这时候可以把“是否要现场实现一个heap”的问题抛回给面试官。在大部分情况下是不需要的,或者说是次要的。这时候可以先假设有这样一个heap的library存在(就像其它语言一样),直接调用即可。

语言只是实现算法,解决问题的工具。并不会因为某个语言本身不存在某个数据结构,或者是存在某个特殊的算法(比如next permutation),就会因此让你的面试结果被扣分,或者是加分。如果面试官想考的就是heap的实现,那么语言里有这个数据结构,也还是需要自己实现出来。

就我自己的经验而言,有时候面试官会追问heap的实现,这时候如果能够答出大概的实现方法,比如使用array,如何实现heapifyDown,heapifyUp等等,其实反而是一个加分的表现机会。

评分

参与人数 4大米 +13 收起 理由
admin + 10 很有用的信息!
gagawoahlala + 1 给你点个赞!
tynsky + 1 赞一个
Elvetia + 1 赞一个

查看全部评分

回复

使用道具 举报

推荐
SoWhat0309 2022-4-16 11:43:11 | 只看该作者
全局:
毕竟跑在浏览器里的lisp,要是带个好用点的堆的话估计也能抛弃python了(
回复

使用道具 举报

🔗
gagawoahlala 2022-4-16 10:32:47 | 只看该作者
全局:
楼主,你在面试的时候如果碰到了PQ的题咋办?要现场实现一个heap吗?
回复

使用道具 举报

🔗
ny0707 2022-4-16 10:54:17 来自APP | 只看该作者
全局:
我感觉面试如果考 PQ,一种是完整实现,另一种是基于这个解决问题,可以简单数组加排序实现,默认复杂度是 logn 就好
回复

使用道具 举报

🔗
hys928 2022-4-16 11:27:59 来自APP | 只看该作者
全局:
gagawoahlala 发表于 2022-04-15 19:32:47
楼主,你在面试的时候如果碰到了PQ的题咋办?要现场实现一个heap吗?
前端不会面PQ😹 类似Google这样面到了也只需要引用一个类似heapify的lib function就好了 也不用跑
回复

使用道具 举报

🔗
sybzd 2022-4-16 15:51:54 | 只看该作者
全局:
你这个heap是O(n)的complexity,很多题过不去的。
js和python刷题的硬伤是没有native red black tree
回复

使用道具 举报

🔗
 楼主| zachzwy 2022-4-17 02:20:12 | 只看该作者
全局:
sybzd 发表于 2022-4-16 00:51
你这个heap是O(n)的complexity,很多题过不去的。
js和python刷题的硬伤是没有native red black tree

你要是仔细看的话会发现这是nlgn的复杂度。我做的所有PQ的题目都可以通过。
如果你用了我的实现方法而没有通过的话,欢迎分享具体的题目。我们可以进一步探讨。

我个人一直认为每种语言都有自己的优缺点。单就刷题面试找工作而言,语言差异所带来的区分度其实是可以忽略不计的,不存在所谓的硬伤。
回复

使用道具 举报

🔗
sybzd 2022-4-17 06:53:52 | 只看该作者
全局:
zachzwy 发表于 2022-4-16 11:20
你要是仔细看的话会发现这是nlgn的复杂度。我做的所有PQ的题目都可以通过。
如果你用了我的实现方法而没 ...

push的里面用了while,而且是根据index走的,肯定不是log n
面试的时候考个heap的题,你光抄heap的code都抄不完,怎么不是硬伤。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表