<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[cyen6 - Medium]]></title>
        <description><![CDATA[一個曾經在攝影棚打滾，現在跑來寫程式的三類人，喜歡寫文章，但常常拖延症發作而拖稿，興趣廣泛，舉凡棒球、歷史、人類學，人生目標是走遍世界的每一個角落。 - Medium]]></description>
        <link>https://medium.com/cyen6?source=rss----ca317c46c7c7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>cyen6 - Medium</title>
            <link>https://medium.com/cyen6?source=rss----ca317c46c7c7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:34:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/cyen6" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[找回有 git add 但沒有 commit 的紀錄]]></title>
            <link>https://medium.com/cyen6/%E6%89%BE%E5%9B%9E%E6%9C%89-git-add-%E4%BD%86%E6%B2%92%E6%9C%89-commit-%E7%9A%84%E7%B4%80%E9%8C%84-1c0a12ab8077?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/1c0a12ab8077</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[回復]]></category>
            <category><![CDATA[紀錄]]></category>
            <category><![CDATA[git-add]]></category>
            <category><![CDATA[救回]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 14:39:02 GMT</pubDate>
            <atom:updated>2022-10-15T14:39:02.009Z</atom:updated>
            <content:encoded><![CDATA[<p>事情是這樣的，有天當我大致完成了專案，正準備 git commit 後推上 github 時，發現之前 rebase 的東西還沒有完成，這時候的我不知道是哪根筋不對勁，竟然輸入了 git rebase --abort，enter 下去的那瞬間我就後悔了，我今天做的東西都不見了！！！乾，剩下兩小時就要下班，而且今天就是 deadline。</p><p>跟同事求救，試了一下 reflog，他雖然會把 Head 的改變都記錄下來，但 git add 不包含在內。正當我就要放棄的時候，發現 add 似乎也會有紀錄喔！</p><h3>找出 git add 的紀錄</h3><p>這些紀錄會放在 .git/objects 這個資料夾裡面，所以可以用 find .git/objects -type f 去找 .git/objects 裡面類型為一般檔案的檔案。</p><p>找到檔案之後可以透過 xargs 這個指令來協助做一些事情，例如 find . -name “*.c” | xargs rm -f 就代表，在目前資料夾中找到 .c 的檔案，再將這些檔案作為變數給 rm -f來刪除，效果就會像是</p><pre>rm -f ./folder2/file3.c ./folder1/file2.c ./folder1/file1.c</pre><p>因此我們可以將剛剛找到的檔案，透過這個指令列出後，由新排到舊 find .git/objects -type f | xargs ls -lt，-lt 是從新到舊，反過來是 -ltr</p><p>因為紀錄太多不可能全列出來，所以最後我們用 sed 30q 列出 30 個，合起來就是 find .git/objects -type f | xargs ls -lt | sed 30q</p><h3>找回實際的改動</h3><p>這時候在 console 就可以看到先前動作的紀錄了</p><pre>r--r--r--. 1 derek derek 1489 10月 14 15:10 .git/objects/06/1475277062fe902da80a45f17a5bf8a1b6381f</pre><pre>-r--r--r--. 1 derek derek 490 10月 14 14:49 .git/objects/30/d64a4ba19b36442c6203f815c2e6d81e9b2ef5 </pre><pre>-r--r--r--. 1 derek derek 145 10月 14 14:49 .git/objects/29/2341c66170b0586f3cfe2942e6af9d3a20a71a </pre><pre>-r--r--r--. 1 derek derek 151 10月 14 14:49 .git/objects/33/db66ac316d4b46b12b01169eb766d2b2cd540e </pre><pre>-r--r--r--. 1 derek derek 437 10月 14 14:49 .git/objects/a4/da37f884129336641f855b2122bc3c89016a44 </pre><pre>-r--r--r--. 1 derek derek 54 10月 14 14:49 .git/objects/a6/63f5228363b094a10e5fe5403eed69b8f89c9c</pre><pre>...總共 30 筆</pre><p>要查看紀錄的內容，我們要使用資料夾名稱和檔案的名稱，例如第一個 .git/objects/06/1475277062fe902da80a45f17a5bf8a1b6381f，我們去掉中間的 / 得到 061475277062fe902da80a45f17a5bf8a1b6381f，然後使用 git show 061475277062fe902da80a45f17a5bf8a1b6381f &gt; recover.txt，把內容丟到 recover.txt 裡面，就可以得到動作的細節了。</p><p>靠著這樣的比對，我也在時間內陸續救回原本以為不見的檔案，也趁著這次經驗學到了一課，真是可喜可賀！</p><h3>Reference</h3><p><a href="https://blog.gtwang.org/linux/xargs-command-examples-in-linux-unix/">Linux 系統 xargs 指令範例與教學</a><br><a href="https://www.runoob.com/linux/linux-comm-ls.html">Linux ls 命令</a><br><a href="https://www.jianshu.com/p/311c5e33c705">记一次找回丢失的 git add 未 git commit 的文件历程</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c0a12ab8077" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/%E6%89%BE%E5%9B%9E%E6%9C%89-git-add-%E4%BD%86%E6%B2%92%E6%9C%89-commit-%E7%9A%84%E7%B4%80%E9%8C%84-1c0a12ab8077">找回有 git add 但沒有 commit 的紀錄</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 387 | First Unique Character in a String（Easy）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-387-first-unique-character-in-a-string-easy-647f7653eeeb?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/647f7653eeeb</guid>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[筆記]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[first-unique-character]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 05:30:00 GMT</pubDate>
            <atom:updated>2022-07-23T05:33:11.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 387 | <strong>First Unique Character in a String</strong>（Easy）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cN4534T8Nl8owpp_kbaV1A.png" /></figure><h4>題目：</h4><p><a href="https://leetcode.com/problems/first-unique-character-in-a-string/">First Unique Character in a String</a></p><h4>敘述：</h4><p>Given a string s, <em>find the first non-repeating character in it and return its index</em>. If it does not exist, return -1.</p><h4>限制：</h4><ul><li>1 &lt;= s.length &lt;= 105</li><li>s consists of only lowercase English letters.</li></ul><h4>思路：</h4><p>最簡單的想法就是先跑一遍，把出現的次數記錄下來，再看看第一個沒有重複的值的 index。</p><pre>var firstUniqChar = function(s) {<br>   let char = &#39;&#39;<br>   let map = new Map()<br>   for(let i = 0; i &lt; s.length; i++) {<br>     if(map.has(s[i])) map.set(s[i], Number(map.get(s[i]) + 1))<br>     else map.set(s[i], 1)<br>   }<br> <br>   for(let value of map) {<br>     if(value[1] &lt; 2) {<br>       char = value[0]<br>       break<br>     }<br>   }<br>   return char.length ? s.indexOf(char) : -1 <br>};</pre><p>O(3n)，所以這是一個時間複雜度為 O(n) 的解法。</p><h4>檢討：</h4><p><a href="https://leetcode.com/problems/first-unique-character-in-a-string/discuss/86356/JavaScript-solution">solution1</a></p><p>這篇第一個做法很簡潔，就是使用了 indexOf 和 lastIndexOf 這兩個方法去解，但時間複雜度是 O(n²)。</p><p>第二個做法是我做法的改良版，這樣我就不用跑三次迴圈了（本來就不需要），這樣也比較 make sense。</p><p>下面的留言還有一個解法：</p><pre>function firstUnique(s) {<br>   const set = {};<br>   const order = [];<br>   for (let i = 0; i &lt; s.length; i++) {<br>       if (s[i] in set) order[set[s[i]]][0]++;<br>       else {<br>           order.push([1, i]);<br>           set[s[i]] = order.length-1;<br>       }<br>   }<br> <br>   for (let i = 0; i &lt; order.length; i++) {<br>       if (order[i][0] === 1) return order[i][1];<br>   }<br>   return -1; <br>}</pre><p>雖然會用到更多的儲存空間，但優點是第二次只要去跑出現過的值就可以了，不用順著 s 跑一遍，理論上會更快，然後我覺得 set 可以改成 Map。</p><p><a href="https://hannahpun.gitbook.io/leetcode-note/string/387-first-unique-character-in-a-string">solution2</a></p><p>這裡的解法是用水桶排序，雖然裡面提到可以讓速度變快，但我怎麼覺得這個方法會跟 O(2n) 那個一樣快。</p><h4>Reference</h4><p><a href="https://hannahpun.gitbook.io/leetcode-note/string/387-first-unique-character-in-a-string">387 First Unique Character in a String</a></p><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=647f7653eeeb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-387-first-unique-character-in-a-string-easy-647f7653eeeb">Leetcode 筆記 — 387 | First Unique Character in a String（Easy）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 74 | Search a 2D Matrix（Medium）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-74-search-a-2d-matrix-medium-a50973855eb?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/a50973855eb</guid>
            <category><![CDATA[筆記]]></category>
            <category><![CDATA[search-a-2d-matrix]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 05:15:53 GMT</pubDate>
            <atom:updated>2022-07-23T05:15:53.781Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 74 | Search a 2D Matrix（Medium）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVkjXJLlHWsI_20OOSny8w.png" /></figure><h4>題目：</h4><p><a href="https://leetcode.com/problems/search-a-2d-matrix/">Search a 2D Matrix</a></p><h4>敘述：</h4><p>Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:</p><ul><li>Integers in each row are sorted from left to right.</li><li>The first integer of each row is greater than the last integer of the previous row.</li></ul><h4>限制：</h4><ul><li>m == matrix.length</li><li>n == matrix[i].length</li><li>1 &lt;= m, n &lt;= 100</li><li>104 &lt;= matrix[i][j], target &lt;= 104</li></ul><h4>思路：</h4><p>既然這個 matrix 已經排序過了，那就可以先判斷要找哪一行，確定好行之後，再從這一行尋找有沒有和 target 一樣的值。</p><pre>var searchMatrix = function(matrix, target) {<br>   if(matrix[0][0] &gt; target) return false<br>   <br>   const m = matrix.length<br>   const n = matrix[0].length<br> <br>   const searchTarget = (line) =&gt; {<br>     for(let i = 0; i &lt; n; i++) {<br>       if(matrix[line][i] === target) return true<br>     }<br>     return false<br>   }<br> <br>   for(let i = 0; i &lt; m; i++) {<br>     if(matrix[i][n-1] &gt;= target) return searchTarget(i)<br>   }<br>   return false <br>};</pre><p>時間複雜度是 O(m+n)，雖然對是對了，但速度很慢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jP1a7JBataGbQ5_rmrpxuw.png" /></figure><h4>改善：</h4><p>改善的方向我覺得可以朝向選擇怎樣的搜尋法來改進，剛剛的寫法是簡易搜尋法，現在改用 binary search。</p><pre>var searchMatrix = function(matrix, target) {<br>   const m = matrix.length<br>   const n = matrix[0].length<br> <br>   if(matrix[0][0] &gt; target || matrix[m-1][n-1] &lt; target) return false<br> <br>   const searchTarget = (line) =&gt; {<br>     return binary_search(matrix[line], target)<br>   }<br> <br>   function binary_search(list, target) {<br>     let low = 0<br>     let high = list.length - 1<br> <br>     while(low &lt;= high) {<br>       const mid = Math.floor((low + high) / 2)<br>       const guess = list[mid]<br>       if(guess === target) return true<br>       guess &lt; target ? (low = mid + 1) : (high = mid - 1)<br>     }<br>     return false<br>   }<br> <br>   for(let i = 0; i &lt; m; i++) {<br>     if(matrix[i][n-1] &gt;= target) return searchTarget(i)<br>   }<br>   return false <br>};</pre><p>果然速度快了不少</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz0nphSlxnwUfocicoGqTg.png" /></figure><p>我把搜尋行的部分也換成 binary search</p><pre>var searchMatrix = function(matrix, target) {<br>   const m = matrix.length<br>   const n = matrix[0].length<br> <br>   if(matrix[0][0] &gt; target || matrix[m-1][n-1] &lt; target) return false<br> <br>   const searchTarget = (line) =&gt; {<br>     return binary_search(matrix[line], target)<br>   }<br> <br>   function binary_search(list, target) {<br>     let low = 0<br>     let high = list.length - 1<br> <br>     while(low &lt;= high) {<br>       const mid = Math.floor((low + high) / 2)<br>       const guess = list[mid]<br>       if(guess === target) return true<br>       guess &lt; target ? (low = mid + 1) : (high = mid - 1)<br>     }<br>     return false<br>   }<br> <br>   function searchLine(matrix, target) {<br>     let low = 0<br>     let high = matrix.length - 1<br> <br>     while(low &lt;= high) {<br>       const mid = Math.floor((low + high) / 2)<br>       const guess = matrix[mid][matrix[0].length-1]<br>       if(guess === target) return true<br>       guess &lt; target ? (low = mid + 1) : (high = mid - 1)<br>     }<br>     return searchTarget(low, target)<br>   }<br> <br>   return searchLine(matrix, target) <br>};</pre><p>跑得更快了！</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8BjRx8DV8UJD5AKYryZjA.png" /></figure><p>時間複雜度是 O(logm * logn)</p><h4>檢討：</h4><p><a href="https://leetcode.com/problems/search-a-2d-matrix/discuss/26220/Don&#39;t-treat-it-as-a-2D-matrix-just-treat-it-as-a-sorted-list">solution1</a></p><p>這也是一個 binary search 的做法，只是他無視這是一個 2D matrix，因為這是一個已經排列好的 matrix，所以他直接把它當作一個陣列來看。</p><p>可以參考這個會更好理解：<a href="https://www.youtube.com/watch?v=FOa55B9Ikfg&amp;t=663s">https://www.youtube.com/watch?v=FOa55B9Ikfg&amp;t=663s</a></p><p>我也改寫成 JavaScript</p><pre>var searchMatrix = function(matrix, target) {<br>   if(matrix === null || matrix.length === 0) return false<br>   let start = 0<br>   let rows = matrix.length<br>   let cols = matrix[0].length<br>   let end = rows * cols - 1<br>   while( start &lt;= end) {<br>     const mid = Math.floor((start + end) / 2)<br>     if(matrix[Math.floor(mid / cols)][mid % cols] === target) return true<br>     matrix[Math.floor(mid / cols)][mid % cols] &lt; target ? start = mid + 1 : end = mid - 1<br>   }<br>   return false <br>};</pre><p>關於為什麼是 i / cols 和 i % cols，可以參考這邊：<a href="https://www.youtube.com/watch?v=FOa55B9Ikfg&amp;t=446s">https://www.youtube.com/watch?v=FOa55B9Ikfg&amp;t=446s</a></p><p><a href="https://leetcode.com/problems/search-a-2d-matrix/discuss/825096/JavaScript-solution-stairCase-method">solution2</a></p><p>另外還看到一種 staircase method，但其實就跟我的解法差不多。</p><h4>Recap</h4><p>複習一下 <a href="https://medium.com/cyen6/%E7%B0%A1%E6%98%93%E6%90%9C%E5%B0%8B%E6%B3%95-sequential-search-%E4%BA%8C%E5%85%83%E6%90%9C%E5%B0%8B%E6%B3%95-binary-search-fde970280cb2">binary search</a></p><h4>Reference</h4><p><a href="https://www.youtube.com/watch?v=FOa55B9Ikfg">Search A 2D Sorted Matrix — Fundamentals of Search Space Reduction</a></p><h4>Vocabulary</h4><ul><li>modulo -取餘數，可以簡稱為 mod</li></ul><p>6 % 4 six mod four<br>6 / 4 six divided by four</p><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a50973855eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-74-search-a-2d-matrix-medium-a50973855eb">Leetcode 筆記 — 74 | Search a 2D Matrix（Medium）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 36 | Valid Sudoku（Medium）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-36-valid-sudoku-medium-f28d917df435?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/f28d917df435</guid>
            <category><![CDATA[valid-sudoku]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[筆記]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 04:26:48 GMT</pubDate>
            <atom:updated>2022-07-23T04:42:33.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 36 | Valid Sudoku（Medium）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5qnsMBP0yGPbfhFQ_LX2g.png" /></figure><h4>題目：</h4><p><a href="https://leetcode.com/problems/valid-sudoku/">Valid Sudoku</a></p><h4>敘述：</h4><p>Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated <strong>according to the following rules</strong>:</p><ol><li>Each row must contain the digits 1-9 without repetition.</li><li>Each column must contain the digits 1-9 without repetition.</li><li>Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.</li></ol><p><strong>Note:</strong></p><ul><li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li><li>Only the filled cells need to be validated according to the mentioned rules.</li></ul><h4>限制：</h4><ul><li>board.length == 9</li><li>board[i].length == 9</li><li>board[i][j] is a digit 1-9 or &#39;.&#39;.</li></ul><h4>思路：</h4><p>因為要符合三個條件，所以最簡單就是分別判斷三個條件即可</p><pre>var isValidSudoku = function(board) {<br>   const re_num = /^[1-9]$/<br>   const re_dot = /\./<br>   let result = true</pre><pre>   //check rows<br>   board.forEach(row =&gt; {<br>     const map = new Map()<br>     row.forEach(ele =&gt; {<br>       if(re_num.test(ele) || re_dot.test(ele)) {<br>         if(re_num.test(ele)) {<br>           map.has(ele) ? result = false : map.set(ele, true)<br>         }<br>       } else {<br>         result = false<br>       }<br>     })<br>   });</pre><pre>   //check columns<br>   if(!result) return result<br>   for(let i = 0; i &lt; 9; i++) {<br>     const map = new Map()<br>     for(let j = 0; j &lt; 9; j++) {<br>       const target = board[j][i]<br>       if(re_num.test(target) || re_dot.test(target)) {<br>         if(re_num.test(target)) {<br>           map.has(target) ? result = false : map.set(target, true)<br>         }<br>       } else {<br>         result = false<br>       }<br>     }<br>   }</pre><pre>   //check sub-boxes<br>   if(!result) return result<br>   let x = 0<br>   let y = 0<br>   while(x &lt; board.length) {<br>     const map = new Map()<br>     for(let i = x; i &lt; x + 3; i++) {<br>       for(let j = y; j &lt; y + 3; j++) {<br>         const target = board[i][j]<br>         if(re_num.test(target) || re_dot.test(target)) {<br>           if(re_num.test(target)) {<br>             map.has(target) ? result = false : map.set(target, true)<br>           }<br>         } else {<br>           result = false<br>         }<br>       }<br>     }<br>     y = y + 3<br>     if( y + 3 &gt; board.length ) {<br>       y = 0<br>       x = x + 3<br>     }<br>   }<br>   return result<br>};</pre><p>三個檢查都要順過全部的值，所以時間複雜度應該是 O(n)</p><h4>改善：</h4><p>雖然說時間複雜度是 O(n)，但其實是整整跑了三次，所以要變快應該可以在 iterate 每一個值的時候就順便把這三件事都做好，但我目前還沒想到好的方法。</p><h4>檢討：</h4><p>在檢討的時候才赫然發現，限制裡面就有說值不是 1~9 就是 . 了，所以其實我沒有必要去判斷他是不是 1~9</p><p><a href="https://leetcode.com/problems/valid-sudoku/discuss/1647166/Javascript">solution</a></p><p>看到這個方法的時候覺得好聰明喔，直接創一個 Set，然後依照所要被判斷的東西，填入相對應的值。</p><p>其中在檢查 sub-boxes 的時候也用到了 i/3 這種方式，跟在 <a href="https://leetcode.com/problems/reshape-the-matrix/discuss/102491/Java-Concise-O(nm)-time">Reshape the Matrix</a> 看到的解法是一樣的概念。</p><p>不過因為每次都要用 set.has() 來搜尋，所以我這邊覺得用 Map 會更好，因為 Set 搜尋的時間複雜度是 O(n)，Map 是 O(1)。</p><h4>Recap</h4><p>在解題的時候有用到 regex，雖然最後發現其實是不需要的，但還是可以來複習一下。</p><p>^ 表示開頭，$ 表示在結尾，所以如果想要抓到範圍 1–9 的數字，不能只寫成 /[1–9]/，這樣你就算給 1991 也會被抓到，因為這四個數字都符合條件，要符合條件就要寫成 /^[1–9]$/</p><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f28d917df435" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-36-valid-sudoku-medium-f28d917df435">Leetcode 筆記 — 36 | Valid Sudoku（Medium）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 118 | Pascal’s Triangle（Easy）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-118-pascals-triangle-easy-82a4f454fc4e?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/82a4f454fc4e</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[筆記]]></category>
            <category><![CDATA[帕斯卡三角形]]></category>
            <category><![CDATA[pascal-triangle]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 12:02:58 GMT</pubDate>
            <atom:updated>2022-07-02T12:02:46.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 118 | Pascal’s Triangle（Easy）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EY51vOLX4dDBvOWGQE74DA.png" /></figure><h4>題目：</h4><p><a href="https://leetcode.com/problems/pascals-triangle/">Pascal’s Triangle</a></p><h4>敘述：</h4><p>Given an integer numRows, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p><p>In <strong>Pascal’s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*axQvhSiNEERy8w-X4NmgRA.png" /></figure><h4>限制：</h4><ul><li>1 &lt;= numRows &lt;= 30</li></ul><h4>思路：</h4><p>可以觀察到這個帕斯卡三角形每一列的第一個和最後一個數都是 1，其他的數都是上一列 index-1 和 index 的值相加，所以直覺來說我們可以一列一列來做。</p><pre>var generate = function(numRows) {<br>   let arr = []<br>   let row = 0   while(row &lt; numRows) {<br>     let temp_arr = []<br>     for(let i = 0; i &lt; row + 1; i++) {<br>       if(i === 0 || i === row) temp_arr.push(1)<br>       else {<br>         let lastest_row = arr[arr.length - 1]<br>         temp_arr.push(lastest_row[i-1] + lastest_row[i])<br>       }<br>     }<br>     row++<br>     arr.push(temp_arr)<br>   }<br>   return arr <br>};</pre><p>時間複雜度是 O(n log n)</p><h4>檢討：</h4><p><a href="https://leetcode.com/problems/pascals-triangle/discuss/824688/Javascript-Solution%3A118">solution</a></p><p>看到一個概念相同，但更簡潔的寫法</p><pre>let generate = function(numRows) {<br>    let final=[];<br>    for(let i=0;i&lt;numRows;i++){<br>        final[i]=[];<br>        final[i][0]=final[i][i]=1;<br>        for(let j=1;j&lt;i;j++){<br>            final[i][j]=final[i-1][j]+final[i-1][j-1];<br>        }<br>    }<br>    return final;<br>};</pre><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82a4f454fc4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-118-pascals-triangle-easy-82a4f454fc4e">Leetcode 筆記 — 118 | Pascal’s Triangle（Easy）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 566 | Reshape the Matrix（Easy）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-566-reshape-the-matrix-easy-e36af28789eb?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/e36af28789eb</guid>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[筆記]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 11:47:47 GMT</pubDate>
            <atom:updated>2023-03-23T04:06:25.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 566 | Reshape the Matrix（Easy）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIoJWcr6nMTNl4oL7kXJGw.png" /></figure><h4>題目：</h4><p><a href="https://leetcode.com/problems/reshape-the-matrix/">Reshape the Matrix</a></p><h4>敘述：</h4><p>In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.</p><p>You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.</p><p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p><p>If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p><h4>限制：</h4><ul><li>m == mat.length</li><li>n == mat[i].length</li><li>1 &lt;= m, n &lt;= 100</li><li>-1000 &lt;= mat[i][j] &lt;= 1000</li><li>1 &lt;= r, c &lt;= 300</li></ul><h4>思路：</h4><p>這一題直覺的想法是把原本的陣列都先壓扁，然後依照指定的行、列輸出，如果 input 值數目和 output 的總數不符合的話，就不做 reshape。</p><pre>var matrixReshape = function(mat, r, c) {<br>   const flat = mat.reduce((acc, val) =&gt; acc.concat(val))<br>   if(flat.length !== r * c) return mat<br>   let arr = []<br>   let current_row = 1<br>   let current_index = 0<br>   while(current_row &lt;= r) {<br>     let temp_arr = []<br>     for(let i = current_index; i &lt; current_index + c; i++) {<br>       temp_arr.push(flat[i])<br>     }<br>     arr.push(temp_arr)<br>     current_index += c<br>     current_row++<br>   }<br>   return arr <br>};</pre><p>reduce 和 concat 時間複雜度都是 O(n)，O(n) + O(n) = O(n)，while 跟 for loop 加起來是把全部的值跑一遍，所以也是 O(n)。</p><h4>檢討：</h4><p><a href="https://leetcode.com/problems/reshape-the-matrix/discuss/734753/Javascript-ES6-simple-solution">solution1</a></p><p>這個方法時間複雜度比較差，但很簡潔</p><pre>var matrixReshape = function (nums, r, c) {<br>   var arr = nums.flat();<br>   if (r * c != arr.length) return nums;<br>   <br>   var res = [];<br>   while (arr.length) res.push(arr.splice(0, c));<br>   return res; <br>};</pre><p><a href="https://leetcode.com/problems/reshape-the-matrix/discuss/102491/Java-Concise-O(nm)-time">solution2</a></p><p>這個雖然不是 javascript，但看起來很厲害，他利用商＆餘數來決定要取值的位置，以及這個值要放在哪裡。</p><p>後來發現在這題的 hint 4 有提到一樣的觀念</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1S1a3LhnzIYwjfB8K36zA.png" /></figure><p>實作出來大概會長這樣</p><pre>var matrixReshape = function(mat, r, c) {<br>  let m = mat.length, n = mat[0].length<br>  if(m*n !== r*c) return mat<br>  let arr = []<br>  for(let i = 0; i &lt; r*c; i++) {<br>    const row = Math.floor(i/c)<br>    if(!arr[row]) arr.push([])<br>    arr[row].push(mat[Math.floor(i/n)][i%n])<br>  }<br>  return arr<br>};</pre><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e36af28789eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-566-reshape-the-matrix-easy-e36af28789eb">Leetcode 筆記 — 566 | Reshape the Matrix（Easy）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 121 | Best Time to Buy and Sell Stock（Easy）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-121-best-time-to-buy-and-sell-stock-easy-70f1ffa2f3d9?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/70f1ffa2f3d9</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[筆記]]></category>
            <category><![CDATA[leetcode-121]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 10:07:32 GMT</pubDate>
            <atom:updated>2022-07-02T10:07:22.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 121 | Best Time to Buy and Sell Stock（Easy）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDwx43dgqEXy-dVAnDKl7g.png" /></figure><p>股市賺錢的秘訣沒有別的，就是低買高賣，看來這題的作者也發現這一點了呢 XD</p><h4>題目：</h4><p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/">Best Time to Buy and Sell Stock</a></p><h4>敘述：</h4><p>You are given an array prices where prices[i] is the price of a given stock on the ith day.</p><p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p><p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return 0.</p><h4>限制：</h4><ul><li>1 &lt;= prices.length &lt;= 105</li><li>0 &lt;= prices[i] &lt;= 104</li></ul><h4>思路：</h4><p>其實這題很簡單，問一下阿南德哪天買哪天賣，就是答案了（亂講</p><p>最簡單的方式就是，依序看每天的價格，如果後面有比他高的價格就把他們的差記錄下來，最後輸出最高的值，如果所有的差都小於等於 0，就回傳 0，可以簡單寫成下面這樣</p><pre>var maxProfit = function(prices) {<br>   let profit = 0<br>   for(let i = 0; i &lt; prices.length - 1; i++) {<br>     for(let j = i+1; j &lt; prices.length; j++) {<br>       const tempProfit = prices[j] - prices[i]<br>       tempProfit &gt; profit ? profit = tempProfit : &#39;&#39;<br>     }<br>   }<br>   return profit &gt; 0 ? profit : 0 <br>};</pre><p>這樣的時間複雜度是 O(n²)</p><h4>改善：</h4><p>改善的方法也滿簡單的，就是動態去計算最低和相對最高的值，這樣順著 array 跑完一遍之後就會得到答案了。</p><pre>var maxProfit = function(prices) {<br>   let current_low = prices[0]<br>   let current_high = 0<br>   let i = 1<br>   while(i &lt; prices.length) {<br>     if(prices[i] &lt; current_low) {<br>       current_low = prices[i]<br>       current_high = 0<br>     } else if(prices[i] &gt; current_high) {<br>       current_high = prices[i]<br>     }<br>     i++<br>   }<br>   return current_high - current_low &gt; 0 ? current_high - current_low : 0 <br>};</pre><p>跑下去是錯的，因為沒有考慮到最後一天是下跌的情況</p><p>所以就稍微改一下判斷</p><pre>var maxProfit = function(prices) {<br>   let current_low = prices[0]<br>   let current_high = 0<br>   let profit = 0<br>   let i = 1<br>   while(i &lt; prices.length) {<br>     if(prices[i] &lt; current_low) {<br>       current_high - current_low &gt; profit ? profit = current_high - current_low : &#39;&#39;<br>       current_low = prices[i]<br>       current_high = 0<br>     } else if(prices[i] &gt; current_high) {<br>       current_high = prices[i]<br>     }<br>     i++<br>   }<br>   current_high - current_low &gt; profit ? profit = current_high - current_low : &#39;&#39;<br>   return profit &gt; 0 ? profit : 0 <br>};</pre><p>時間複雜度已經降到 O(n)，但竟然超時了？</p><h4>檢討：</h4><p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/1735550/Python-Javascript-Easy-solution-with-very-clear-Explanation">solution1</a></p><p>這個解法是用 two pointer 的方式</p><p>慢的指針（walker）先指向第一天的價格，快的指針（runner）指向第二天的，如果 runner 的價格高於 walker 的，這之間的價差去跟目前紀錄的 max_profit 比較，取高的那個，然後 runner 往下一天移動，walker 不動。</p><p>（畢竟 runner 比 walker 快也是很正常的）</p><p>直到 runner 的值比 walker 低，walker 追上 runner，最後算出 max_profit。</p><pre>var maxProfit = function(prices) {<br>   let left = 0<br>   let right = 1<br>   let max_profit = 0<br>   while(right &lt; prices.length) {<br>     if(prices[left] &lt; prices[right]) {<br>       let profit = prices[right] - prices[left]<br>       max_profit = Math.max(max_profit, profit)<br>     } else {<br>       left = right<br>     }<br>     right++<br>   }<br>   return max_profit <br>};</pre><p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/39038/Kadane&#39;s-Algorithm-Since-no-one-has-mentioned-about-this-so-far-%3A">solution2</a></p><p>另一個解法是用 Kadane’s Algorithm，看完之後會發現跟之前在做 <a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-53-maximum-subarray-easy-5223a56fa0a0"><strong>Maximum Subarray</strong></a><strong> </strong>看過的解法一樣，一樣是用動態規劃的方法來做。</p><p>但想來想去我還是覺得我的作法應該不至於超時，所以後來東試西試把 current_high — current_low &gt; profit ? profit = current_high — current_low : ’’，改寫成 profit = Math.max(current_high — current_low, profit)，然後就過了？</p><p>是我哪裡沒有想清楚嗎？總覺得跟三元運算子應該無關</p><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70f1ffa2f3d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-121-best-time-to-buy-and-sell-stock-easy-70f1ffa2f3d9">Leetcode 筆記 — 121 | Best Time to Buy and Sell Stock（Easy）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 350 | Intersection of Two Arrays II（Easy）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-350-intersection-of-two-arrays-ii-easy-416263943b8e?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/416263943b8e</guid>
            <category><![CDATA[筆記]]></category>
            <category><![CDATA[array-two]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-350]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 25 Jun 2022 16:19:45 GMT</pubDate>
            <atom:updated>2022-06-25T16:19:35.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 350 | Intersection of Two Arrays II（Easy）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qm4kBo5LxCOkEa6nEJdqqw.png" /></figure><h4>題目：</h4><p><a href="https://leetcode.com/problems/intersection-of-two-arrays-ii/">Intersection of Two Arrays II</a></p><h4>敘述：</h4><p>Given two integer arrays nums1 and nums2, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.</p><h4>限制：</h4><ul><li>1 &lt;= nums1.length, nums2.length &lt;= 1000</li><li>0 &lt;= nums1[i], nums2[i] &lt;= 1000</li></ul><h4>思路：</h4><p>這題要找到兩個陣列之間交集的數，所以就先用很暴力的方法，一個一個去比對</p><pre>var intersect = function(nums1, nums2) {<br>   let arr = []<br>   for(let i = 0; i &lt;= nums1.length; i++) { // O(m)<br>     const index = nums2.indexOf(nums1[i]) // O(n)<br>     if(index &gt;= 0) {<br>       arr.push(nums2.splice(index, 1)[0]) // O(n)<br>     }<br>   }<br>   return arr <br>};</pre><p>時間複雜度 O(m*n)</p><h4>改善：</h4><p>看看能不能把時間複雜度降下來，關鍵在於不要用 splice 去改動 array 的值，因為如果在陣列中間去做變動，時間複雜度就會大幅提升，那要怎麼知道這個值已經出現過或已經算過了呢？結論就是先把陣列都排序好，這樣就一定可以保證後面不會出現小於他的數字。</p><pre>var intersect = function(nums1, nums2) {<br>   nums1.sort((a, b) =&gt; { return a - b })<br>   nums2.sort((a, b) =&gt; { return a - b })<br>   let arr = []<br>   let i = 0<br>   let j = 0<br>   while(i &lt; nums1.length &amp;&amp; j &lt; nums2.length) {<br>     if(nums1[i] === nums2[j]) {<br>       arr.push(nums1[i])<br>       i++<br>       j++<br>     } else {<br>       nums1[i] &lt; nums2[j] ? i++ : j++<br>     }<br>   }<br>   return arr <br>};</pre><p>時間複雜度 O(mlogm+nlogn)</p><h4>檢討：</h4><p>這題有三個 follow up</p><ul><li>What if the given array is already sorted? How would you optimize your algorithm?</li></ul><p>A: 如果已經排序好了可以用我上面這個寫法。</p><ul><li>What if nums1&#39;s size is small compared to nums2&#39;s size? Which algorithm is better?</li></ul><p>A: 如果 nums1 相較於 nums2 小很多，可以用 hash table 先把小的那個記下來，寫成 code 大概會長<a href="https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/579977/Simple-JavaScript-solution">這樣</a>。不管把大或小的 array 做成 hash table，時間複雜度都是 O(m+n)，但空間複雜度取決於那個做成 hash table 的陣列長度。</p><ul><li>What if elements of <em>nums2 </em>are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li></ul><p>A: 如果記憶體大小有限制，而只有 nums2 無法一次把所有 element 帶進來處理，可以先把 nums1 做成 hash table，nums2 再分批拿進去處理，並且把交集的地方記錄下來。</p><p>那如果 nums1 和nums2 都很大，參考<a href="https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82243/Solution-to-3rd-follow-up-question">這篇</a>的說法，可以先用<a href="https://www.youtube.com/watch?v=Bp7fGofslng">外部排序</a>（external sort），再將 nums1 和 nums2 依序 load 進來記憶體裡面處理，並且記錄交集。</p><p>不過下面也有說到這個方法是不切實際的（impractical），因為如果你每次只各拿 nums1, nums2 一個值進來做比較，可能會跑一輩子，所以通常的做法是，從兩個陣列各拿一些資料，利用 <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/discuss/2031883/day02-2-pointer-array-shan-chu-you-xu-shu-zu-zhong-de-zhong-fu-xiang">two-pointer 的方法</a>來找交集。另外也有留言說，如果是放在分散式系統中，可以用 Map-Reduce paradigm，不過這我就沒有研究了。</p><h4>Reference</h4><p><a href="https://ithelp.ithome.com.tw/articles/10262277">Two-pointer 介紹</a><br><a href="https://www.youtube.com/watch?v=Bp7fGofslng">External Merge-Sort | Merge Sort | Data Structure | Appliedroots</a></p><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=416263943b8e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-350-intersection-of-two-arrays-ii-easy-416263943b8e">Leetcode 筆記 — 350 | Intersection of Two Arrays II（Easy）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 88 | Merge Sorted Array（Easy）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-88-merge-sorted-array-easy-160ea3ea484e?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/160ea3ea484e</guid>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[merge-sorted-array]]></category>
            <category><![CDATA[筆記]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 25 Jun 2022 13:50:02 GMT</pubDate>
            <atom:updated>2022-06-25T13:49:54.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 88 | Merge Sorted Array（Easy）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWTH6AFiEm3CWI1rD8CtPg.png" /></figure><h4>題目：</h4><p><a href="https://leetcode.com/problems/merge-sorted-array/">Merge Sorted Array</a></p><h4>敘述：</h4><p>You are given two integer arrays nums1 and nums2, sorted in <strong>non-decreasing order</strong>, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.</p><p><strong>Merge</strong> nums1 and nums2 into a single array sorted in <strong>non-decreasing order</strong>.</p><p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array</em> nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.</p><h4>限制：</h4><ul><li>nums1.length == m + n</li><li>nums2.length == n</li><li>0 &lt;= m, n &lt;= 200</li><li>1 &lt;= m + n &lt;= 200</li><li>109 &lt;= nums1[i], nums2[j] &lt;= 109</li></ul><h4>思路：</h4><p>這題簡單來說就是把兩個已經排序好的 array，依照大小再 merge 起來，所以我就簡單寫成這樣</p><pre>var merge = function(nums1, m, nums2, n) {<br>   if(m === 0 || n === 0) return m === 0 ? nums2 : nums1<br>   <br>   let arr = []<br>   let i = 0<br>   let j = 0<br>   while(arr.length &lt; m+n) {<br>     if(nums1[i] !== 0) {<br>       if(nums1[i] &lt;= nums2[j]) {<br>         arr.push(nums1[i])<br>         i++<br>       } else {<br>         arr.push(nums2[j])<br>         j++<br>       }<br>     } else {<br>       for(let k = j; k &lt; n; k++){<br>         arr.push(nums2[k])<br>       }<br>     }<br>   }<br>   return arr <br>};</pre><p>但後來發現我沒看清楚題目，他是要直接去修改 nums1，而且不能先算出一個 array 再賦值給 nums1。</p><p>所以我這邊先把 nums1 補位的 0 都刪掉，然後再讓 nums1 和 nums2 比大小</p><pre>var merge = function(nums1, m, nums2, n) {<br>   while(nums1.length &gt; m) { // O(n)<br>     nums1.pop()             // O(1)<br>   }<br>   let i = 0<br>   let j = 0<br>   while(j &lt; n) { // O(m)<br>     if(nums1[i] &lt;= nums2[j]) {<br>       i++<br>     } else {<br>       nums1.splice(i, 0, nums2[j]) // O(m)<br>       i++<br>       j++<br>     }<br>   }<br>   return nums1 <br>};</pre><p>時間複雜度是 O(m²)，看起來結果還有很多地方可以改善。</p><h4>改善：</h4><p>我想到的方法是，一樣先把 nums1 後面補位的 0 刪掉，然後把 nums1 &amp; nums2 排列好的順序先放在一個暫時的 array 裡，之後把 nums1 清空之後，再把剛剛暫時的 array 排列放回 nums1 中。</p><pre>var merge = function(nums1, m, nums2, n) {<br>   if(n === 0) return nums1<br>   while(nums1.length &gt; m) { // O(n)<br>     nums1.pop()             // O(1)<br>   }<br>   let arr = []<br>   let i = 0<br>   let j = 0<br>   while(i + j &lt; m + n) { // O(m+n)<br>     if(nums1[i] &lt;= nums2[j] || j &gt;= n) {<br>       arr.push(nums1[i]) // O(1)<br>       i++<br>     } else {<br>       arr.push(nums2[j])<br>       j++<br>     }<br>   }<br>   while(nums1.length &gt; 0) { // O(m)<br>     nums1.pop()             // O(1)<br>   }<br>   nums1.push(...arr)        // O(m+n)<br>   return nums1 <br>};</pre><p>時間複雜度可以改善成 O(n+m+n+m+m+n) = O(3m+3n) = O(m+n)，空間複雜度是 O(m+n)。</p><h4>檢討：</h4><p><a href="https://leetcode.com/problems/merge-sorted-array/discuss/552466/JavaScript-solution">Solution1</a></p><p>這個作法則是不去把補 0 刪掉，直接從兩個 array 的後面往前排序，排好的數直接放到 nums1 裡。</p><p>留言的解法跟原 po 概念一樣，但我覺得比原 po 好懂，時間複雜度 O(m+n)</p><pre>var merge = function (nums1, m, nums2, n) {<br>   let p1 = m - 1;<br>   let p2 = n - 1;<br>   for (let i = nums1.length - 1; i &gt;= 0; i--) {<br>     if (p1 &gt;= 0 &amp;&amp; nums1[p1] &gt;= nums2[p2]) {<br>       nums1[i] = nums1[p1];<br>       p1--;<br>     } else if (p2 &gt;= 0) {<br>       nums1[i] = nums2[p2];<br>       p2--;<br>     }<br>   } <br>};</pre><p>這篇的第一個留言說他覺得讓 nums1 補 0 很怪，留言有人補充說這是因為不是每個語言都像 JavaScript 一樣提供 dynamic arrays，所以需要先配置記憶體給他。</p><p><a href="https://leetcode.com/problems/merge-sorted-array/discuss/29741/Javascript-solution-sharing">Solution2</a></p><p>這篇的做法其實就跟 nums1.concat(nums2).sort((a,b) =&gt; (a — b)) 差不多，但如果要用 concat 的話，記得要先把 nums1 的 0 去掉。</p><p><a href="https://stackoverflow.com/questions/8434726/javascript-concat-running-time">concat 的時間複雜度</a>應該是 O(n)，sort 則是要看是用什麼 sort，可以複習<a href="https://medium.com/cyen6/%E6%BC%94%E7%AE%97%E6%B3%95%E7%AD%86%E8%A8%98-sorting-%E4%B8%8B-3d40970f2590">這篇</a>最下面。</p><p>這邊也複習一下 <a href="https://ithelp.ithome.com.tw/articles/10192800">i++ 和 ++i 的差別</a></p><h4>Recap</h4><p><a href="https://medium.com/cyen6/%E8%B3%87%E6%96%99%E7%B5%90%E6%A7%8B-array-d68bbba64720">資料結構筆記 — Array</a><br><a href="https://medium.com/cyen6/%E6%BC%94%E7%AE%97%E6%B3%95%E7%AD%86%E8%A8%98-sorting-%E4%B8%8B-3d40970f2590">演算法筆記 — Sorting（下）</a></p><h4>Reference</h4><p><a href="https://stackoverflow.com/questions/57763205/what-is-array-prototype-sort-time-complexity">What is Array.prototype.sort() time complexity?</a></p><h4>Vocabulary</h4><ul><li>respectively(adv.) - in a way that relates or belongs to each of the separate people or things you have just mentioned</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGqrAJagG8x6suELz5PABw.png" /></figure><ul><li>one’s two cents - 淺見，可以說 That’s just my two cents 來表示謙虛。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPpW6oTVpucQQWwJ1x8sgg.png" /></figure><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=160ea3ea484e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-88-merge-sorted-array-easy-160ea3ea484e">Leetcode 筆記 — 88 | Merge Sorted Array（Easy）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode 筆記 — 1 | Two Sum（Easy）]]></title>
            <link>https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-1-two-sum-easy-bd0ddc5106a0?source=rss----ca317c46c7c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/bd0ddc5106a0</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[two-sum]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[筆記]]></category>
            <dc:creator><![CDATA[Derek Yen]]></dc:creator>
            <pubDate>Sat, 25 Jun 2022 09:55:25 GMT</pubDate>
            <atom:updated>2022-06-25T13:50:54.762Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leetcode 筆記 — 1 | Two Sum（Easy）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnvlJJDnr4jdvzcPa-vTVA.png" /></figure><p>因為看到 line pay 可以領取夜市優惠券，所以昨天下班直接揪了一團去南機場夜市，不得不說蚵嗲那攤真的厲害，不管蚵嗲或是各式炸物都是料多又好吃，如果之後沒有離那邊太遠，我是會為了這個特地繞過去的。</p><h4>題目：</h4><p><a href="https://leetcode.com/problems/two-sum/">Two Sum</a></p><h4>敘述：</h4><p>Given an array of integers nums and an integer target, return <em>indices of the two numbers such that they add up to </em><em>target</em>.</p><p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> element twice.</p><p>You can return the answer in any order.</p><h4>限制：</h4><ul><li>2 &lt;= nums.length &lt;= 10⁴</li><li>-10⁹ &lt;= nums[i] &lt;= 10⁹</li><li>-10⁹ &lt;= target &lt;= 10⁹</li><li>Only one valid answer exists</li></ul><h4>思路：</h4><p>首先一樣先來個暴力解，從 array 的頭開始往後一個一個配對，一直到相加和 target 相同時，回傳 index</p><pre>function twoSum(nums, target) {<br>   for(let i = 0; i &lt; nums.length; i++) {<br>     for(let j = i+1; j &lt;= nums.length; j++) {<br>       if(nums[i] + nums[j] === target) {<br>         return [i, j]<br>       }<br>     }<br>   }<br>};</pre><p>雖然簡單暴力，但時間複雜度是 O(n²)</p><h4>改善：</h4><p>接下來想看看有沒有更快的解法。因為兩個數相加會等於 target，所以也就是說當我找到某一個數之後，我就會知道和他 match 的數字是多少，如果接下來有看到這個 match 的數，就會是答案。</p><p>那因為我要記錄這個數字以及他的 index，所以使用 JavaScript 的 Map</p><pre>function twoSum(nums, target) {<br>   if(nums.length === 2) return [0,1]<br>   let map = new Map()<br>   for(let i = 0; i &lt;= nums.length; i++) {<br>     if(map.has(nums[i])) {<br>       if(map.get(target - nums[i]) !== null) return [map.get(target - nums[i]), i]<br>     }<br>     map.set(target - nums[i], null)<br>     map.set(nums[i], i)<br>   } <br>};</pre><p>這樣做法的時間複雜度是 O(n)，空間複雜度O(n)</p><h4>檢討：</h4><p><a href="https://leetcode.com/problems/two-sum/discuss/173262/JavaScript-Solution">solution1</a></p><p>後來發現我其實也不用把 target - nums[i] 的數先放進 Map 裡面，這樣反而會讓自己後續的判斷更麻煩，在每一圈先找好 target - nums[i]，然後看他有沒有在 Map 裡就好了，邏輯上更簡單，也不會有很多 edge case 要考慮。</p><p>這邊我覺得作者可以改善的是，可以把 object 改成 Map，因為當他在 if (another in map) 找 another 這個值有沒有在 object 裡時，這個動作的時間複雜度是 O(n)，而 Map 則是 O(1)。</p><h4>Reference</h4><p><a href="https://pjchender.dev/javascript/js-map/">JavaScript Map</a></p><h4>Vocabulary</h4><ul><li>indices - plural of index</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uY6ezkB8gIPhwxfVqGHww.png" /></figure><blockquote>回<a href="https://medium.com/cyen6/leetcode-%E6%96%B0%E6%89%8B%E6%8C%91%E6%88%B0-75b4ce40ce87">總表</a>看其他解題筆記＆學習筆記</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd0ddc5106a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyen6/leetcode-%E7%AD%86%E8%A8%98-1-two-sum-easy-bd0ddc5106a0">Leetcode 筆記 — 1 | Two Sum（Easy）</a> was originally published in <a href="https://medium.com/cyen6">cyen6</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>