<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>leetcode on Shiglass</title>
    <link>https://hirotoshimizu.github.io/categories/leetcode/</link>
    <description>Recent content in leetcode on Shiglass</description>
    <generator>Hugo -- gohugo.io</generator>
    <lastBuildDate>Sun, 12 Dec 2021 05:16:29 +0900</lastBuildDate><atom:link href="https://hirotoshimizu.github.io/categories/leetcode/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Longest Palindromic Substring</title>
      <link>https://hirotoshimizu.github.io/posts/longest-palindromic-substring/</link>
      <pubDate>Sun, 12 Dec 2021 05:16:29 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/longest-palindromic-substring/</guid>
      <description>https://leetcode.com/problems/longest-palindromic-substring/
class Solution: def longestPalindrome(self, s: str) -&amp;gt; str: res = &amp;#39;&amp;#39; for i in range(len(s)): # odd case tmp = self.helper(s, i, i) if len(tmp) &amp;gt; len(res): res = tmp # even tmp = self.helper(s, i, i+1) if len(tmp) &amp;gt; len(res): res = tmp return res def helper(self, s, l, r): while l &amp;gt;= 0 and r &amp;lt; len(s) and s[l] == s[r]: l -= 1 r += 1 return s[l+1:r] </description>
    </item>
    
    <item>
      <title>Longest Increasing Subsequence</title>
      <link>https://hirotoshimizu.github.io/posts/longest-increasing-subsequence/</link>
      <pubDate>Sun, 12 Dec 2021 04:07:10 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/longest-increasing-subsequence/</guid>
      <description>https://leetcode.com/problems/longest-increasing-subsequence/
LIS はどんな場合でも最低1になるので、 1を入れた、list を作る。
reverse order でループし、 ネストしたループで最初にループしている i 以降の数と比較する。
nums[i] と nums[j] で nums[i] が小さい場合、 subsequence となるので、 LIS[i] に max(LIS[i], 1 + LIS[j]) を入れる。 j は i 以降の数字を見ているので、max()を使わないと LISの最後の 1 で置き換えて 2 となってしまうので注意。
class Solution: def lengthOfLIS(self, nums: List[int]) -&amp;gt; int: LIS = [1] * len(nums) for i in range(len(nums) - 1, -1, -1): for j in range(i + 1, len(nums)): if nums[i] &amp;lt; nums[j]: LIS[i] = max(LIS[i], 1 + LIS[j]) return max(LIS) </description>
    </item>
    
    <item>
      <title>Longest Common Subsequence</title>
      <link>https://hirotoshimizu.github.io/posts/longest-common-subsequence/</link>
      <pubDate>Sat, 11 Dec 2021 20:20:50 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/longest-common-subsequence/</guid>
      <description>https://leetcode.com/problems/longest-common-subsequence/
2d grid を作る。 row, col にそれぞれ、1行、1列追加して 0 を入れる。
grid の右下からループし、 縦横が同じ文字でマッチしたら、斜め左上に進む。 その際に1を足す。
マッチしなかったら、右横か下のどちらか大きい数字を入れる。
ループが終わりgrid[0][0] の箇所に 1番長い subsequence の数が入る。
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -&amp;gt; int: dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] for i in range(len(text1) - 1, -1, -1): for j in range(len(text2) - 1, -1, -1): if text1[i] == text2[j]: dp[i][j] = 1 + dp[i + 1][j + 1] else: dp[i][j] = max(dp[i + 1][j], dp[i][j + 1]) return dp[0][0] </description>
    </item>
    
    <item>
      <title>Traverse a Tree</title>
      <link>https://hirotoshimizu.github.io/posts/traverse-a-tree/</link>
      <pubDate>Fri, 22 Oct 2021 03:47:59 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/traverse-a-tree/</guid>
      <description>F / \ B G / \ \ A D I / \ / C E H  Pre-order Traversal root left subtree right subtree
F B A D C E G I H
https://leetcode.com/problems/binary-tree-preorder-traversal/
Iterative approach
class Solution(object): def preorderTraversal(self, root: Optional[TreeNode]) -&amp;gt; List[int]: &amp;#34;&amp;#34;&amp;#34; :type root: TreeNode :rtype: List[int] &amp;#34;&amp;#34;&amp;#34; res, stack = [], [(root, False)] while stack: node, visited = stack.pop() if node: if visited: res.append(node.val) else: stack.</description>
    </item>
    
    <item>
      <title>Search Insert Position</title>
      <link>https://hirotoshimizu.github.io/posts/search-insert-position/</link>
      <pubDate>Thu, 21 Oct 2021 23:03:19 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/search-insert-position/</guid>
      <description>https://leetcode.com/problems/search-insert-position/
algorithm の runtime は O(log n) である必要があるため、 binary search で target の数の位置を調べる。
変数 left に 0、 right に len(nums) - 1 を設定する。
(left + right) // 2 で真ん中の値が取得出来るので、 真ん中の位置を mid とする。
nums の mid の値が target なら、mid の index の値を返す。 もし、target の値が mid より大きい場合、 left を mid + 1 にする。 target の値が mid より小さい場合、 right を mid - 1 にする。
[1, 3, 5, 6] で target = 2 の場合、</description>
    </item>
    
    <item>
      <title>Remove Duplicates From Sorted Array</title>
      <link>https://hirotoshimizu.github.io/posts/remove-duplicates-from-sorted-array/</link>
      <pubDate>Thu, 21 Oct 2021 12:17:05 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/remove-duplicates-from-sorted-array/</guid>
      <description>nums = [0,0,1,1,1,2,2,3,3,4] の重複をなくすようにするので、下記のようになる。
nums = [0,1,2,3,4,,,,,_]
pointer を 2つ使う。
最初の数字は必ずユニークになるので、 left = 1　とする。
right は for でループさせながら icrement していく。
non-decreasing order なので、 right の値と right - 1　を比較して、 違う値なら一番初めに現れるユニークの数字だとわかる。
そのためその数字を left pointer がある位置に入れる。 その後、 left pointer をicrementする。
最終的に left pointer の位置がユニークな数の出現回数となるので、 その値を return する。
class Solution: def removeDuplicates(self, nums: List[int]) -&amp;gt; int: left = 1 for right in range(1, len(nums)): if nums[right] != nums[right - 1]: nums[left] = nums[right] left += 1 return left </description>
    </item>
    
    <item>
      <title>Remove Linked List Elements</title>
      <link>https://hirotoshimizu.github.io/posts/remove-linked-list-elements/</link>
      <pubDate>Thu, 21 Oct 2021 09:51:02 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/remove-linked-list-elements/</guid>
      <description>sentinel ノードは Linked List を空にせず、ヘッドレスにしないようにする。
アルゴリズムは
sentinel ノードをセットする。
curr と prev のポインターを設定する。
curr が null でない場合、ループする。
curr.val が 削除する値の場合、
class Solution: def removeElements(self, head: Optional[ListNode], val: int) -&amp;gt; Optional[ListNode]: sentinel = ListNode(next=head) prev, curr = sentinel, head while curr: if curr.val == val: prev.next = curr.next else: prev = curr curr = curr.next return sentinel.next </description>
    </item>
    
    <item>
      <title>Path Sum</title>
      <link>https://hirotoshimizu.github.io/posts/path-sum/</link>
      <pubDate>Thu, 21 Oct 2021 08:21:08 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/path-sum/</guid>
      <description>https://leetcode.com/problems/path-sum/solution/
ノードがリーフでない場合は、子に対してhasPathSumメソッドを再帰的に呼び出し、合計を現在のノードの値だけ減らす。
ノードがリーフの場合、現在の合計がゼロであるかどうか、つまり最初の合計が検出されたかどうかを確認します。
Base case は、root が none ということはリーフの下の node を確認してるので、sum が 0 になっていないので False を返す。
class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -&amp;gt; bool: if not root: return False targetSum -= root.val if not root.left and not root.right: # if reach a leaf return targetSum == 0 return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum) </description>
    </item>
    
    <item>
      <title>Isomorphic Strings</title>
      <link>https://hirotoshimizu.github.io/posts/isomorphic-strings/</link>
      <pubDate>Thu, 21 Oct 2021 05:16:53 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/isomorphic-strings/</guid>
      <description>https://leetcode.com/problems/isomorphic-strings/
s と t をマッピングして考える。 この際、同じ文字なのに違う文字がマッピングされる場合
isomorphic にならない。
ex. foo bar
 | f → b | | o → a | | o → r |  | b → f | | a → o | | r → o | o が a と r にマッピングされているので、 isomorphic にならず、false になる。
class Solution: def isIsomorphic(self, s: str, t: str) -&amp;gt; bool: mapST, mapTS = {}, {} for c1, c2 in zip(s, t): if((c1 in mapST and mapST[c1] !</description>
    </item>
    
    <item>
      <title>Min Stack</title>
      <link>https://hirotoshimizu.github.io/posts/min-stack/</link>
      <pubDate>Wed, 20 Oct 2021 14:48:04 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/min-stack/</guid>
      <description>https://leetcode.com/problems/min-stack/solution/
2つの stack を使う。 1つ目の stack は普通のstackを使うように扱う。(Stack) 2つ目の stack は現在の minimum をトラックするのに使う。(MinStack)
MinStack の pushメソッドは現在の値が stack の top より小さい場合、 push される。
popメソッドは Stack のみからpopすると MinStack と合わなくなるので、 If top of main_stack == top of min_tracker_stack: min_tracker_stack.pop() の処理が必要になる。
class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, x: int) -&amp;gt; None: self.stack.append(x) if not self.min_stack or x &amp;lt;= self.min_stack[-1]: self.min_stack.append(x) def pop(self) -&amp;gt; None: if self.min_stack[-1] == self.stack[-1]: self.min_stack.pop() self.</description>
    </item>
    
    <item>
      <title>Valid Anagram</title>
      <link>https://hirotoshimizu.github.io/posts/valid-anagram/</link>
      <pubDate>Wed, 20 Oct 2021 13:01:44 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/valid-anagram/</guid>
      <description>anagram かどうかを調べるには s, t の出現する文字のカウントが同じなら anagram と言える。
回答方法は
 文字数をカウントし、s と t を比較する 文字数をカウントし、s と t を比較する(Counter を使う) sorted を使う  Input: s = &amp;ldquo;anagram&amp;rdquo;, t = &amp;ldquo;nagaram&amp;rdquo;
 文字数をカウントし、s と t を比較する  class Solution: def isAnagram(self, s: str, t: str) -&amp;gt; bool: if len(s)!= len(t): return False count_s, count_t = {}, {} for i in range(len(s)): count_s[s[i]] = 1 + count_s.get(s[i], 0) count_t[t[i]] = 1 + count_t.get(t[i], 0) for c in count_s: if count_s[c] !</description>
    </item>
    
    <item>
      <title>Happy Number</title>
      <link>https://hirotoshimizu.github.io/posts/happy-number/</link>
      <pubDate>Wed, 20 Oct 2021 11:27:43 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/happy-number/</guid>
      <description>パターン1 7 → 49 → 97 → 130 → 10 → 1
パターン2 2 → 4 → 16 → 37 → 30 → 9 → 81 → 65 → 61 → 37
Algorithm
  number n の次の数が何かを調べる
  cycle に入ったかを調べる。
  の調べ方 19 → 1^2 + 9^2 = 82
  変数 output に 0 を代入し、 while で n がある間
n = 19 の場合、
1の位を取得 19 % 10 = 9</description>
    </item>
    
    <item>
      <title>Replace Elements With Greatest Element on Right Side</title>
      <link>https://hirotoshimizu.github.io/posts/replace-elements-with-greatest-element-on-right-side/</link>
      <pubDate>Mon, 18 Oct 2021 20:06:14 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/replace-elements-with-greatest-element-on-right-side/</guid>
      <description>https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/
一番最後が -1 になるので、 変数 right_max に -1 を入れる。
後ろからループしていき、 現在の値 と right_max の大きい値を new_max に入れる。 現在の値に right_max を代入し、 right_max の値に nex_max を代入しループを続ける。
 | 17 | 18 | 5 | 4 | 6 | 1 | -1 18 6 6 6 1 -1
class Solution: def replaceElements(self, arr: List[int]) -&amp;gt; List[int]: right_max = -1 for i in range(len(arr) -1, -1, -1): new_max = max(right_max, arr[i]) arr[i] = right_max right_max = new_max </description>
    </item>
    
    <item>
      <title>Palindrome Linked List</title>
      <link>https://hirotoshimizu.github.io/posts/palindrome-linked-list/</link>
      <pubDate>Mon, 18 Oct 2021 16:55:29 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/palindrome-linked-list/</guid>
      <description>この問題の解き方は pointer を2つ使う。
  真ん中を探す Pointer を2つ使い、fast pointer と fast.next が null になるまで Pinter を進める。 その際 slow pointer が真ん中に位置する。
  後ろ半分を反転させる slow pointer が真ん中に位置しているので、 slow が null になるまでループさせる。
step.1 1 → 2 → 3 → null
prev と curr を憶えておく必要がある。
prev = null curr = 1
curr の next node を temp に入れておく。 temp = 2
null ← 1 2 → 3 → null
step.2 prev = 1 curr = 2 temp = 3</description>
    </item>
    
    <item>
      <title>Merge Sorted Array</title>
      <link>https://hirotoshimizu.github.io/posts/merge-sorted-array/</link>
      <pubDate>Mon, 18 Oct 2021 14:52:25 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/merge-sorted-array/</guid>
      <description>https://leetcode.com/problems/merge-sorted-array/
この問題は pointer を 3つ使う。 1つ目は、nums1 の最後に pointer を設定。 2つ目は、nums1 の m に pointer を設定。 3つ目は、nums2 の 最後に pointer を設定。
 | 1 | 2 | 3 | 0 | 0 | 0 |  ↑ ↑   | 2 | 5 | 6 |  ↑  nums1[m - 1] と nums2[n - 1] の値を比べて、 nums2[n - 1] の値が大きいので、 nums1[last] = nums2[n - 1] を設定する。 そして nums2 の n の pointer を -1 してずらす。 また nums1 の last の pointer も -1 する。</description>
    </item>
    
    <item>
      <title>House Robber</title>
      <link>https://hirotoshimizu.github.io/posts/house-robber/</link>
      <pubDate>Mon, 18 Oct 2021 14:04:56 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/house-robber/</guid>
      <description>https://leetcode.com/problems/house-robber/
隣り合った家は訪れることが出来ないので、 変数 rob1 と rob2 を用意する。
for で全ての家を訪れ、 pointer のある位置＋rob1 と rob2 の大きい値を temp に入れる。
rob1 pointerのある位置の前の前の家 rob2 pointerのある位置のは前の家
rob2 が nums の最後の位置まで行くとループが終わるので return で rob2 を返す。
class Solution: def rob(self, num: List[int])-&amp;gt; int: rob1, rob2 = 0, 0 for n in num: temp = max(rob1 + n, rob2) rob1 = rob2 rob2 = temp return rob2 </description>
    </item>
    
    <item>
      <title>Two Sum Ii Input Array Is Sorted</title>
      <link>https://hirotoshimizu.github.io/posts/two-sum-ii-input-array-is-sorted/</link>
      <pubDate>Mon, 18 Oct 2021 13:31:53 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/two-sum-ii-input-array-is-sorted/</guid>
      <description>https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
この問題は pointer を2つ使い target になる数を探していく。
pointer を left と right に置き、 left と right の合計が target の値と同じかを計算する。
合計が大きい場合は right の pointer を左にずらし、 合計が小さい場合は left の pointer を右にずらしていく。
合計がtarget の値になるまでループして index の位置を返す。
target = 9
 | 1 | 3 | 4 | 5 | 7 | 11 | 　↑　↑
1 + 11 = 12 &amp;gt; 9
 | 1 | 3 | 4 | 5 | 7 | 11 | 　↑　↑</description>
    </item>
    
    <item>
      <title>Find the Town Judge</title>
      <link>https://hirotoshimizu.github.io/posts/find-the-town-judge/</link>
      <pubDate>Sun, 17 Oct 2021 19:23:52 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/find-the-town-judge/</guid>
      <description>https://leetcode.com/problems/find-the-town-judge/
graphの問題で、trust のペア, [a, b] は a から b に向かう directed edge である。
例えば、 N = 5 で trust trust = [[1,3],[2,3],[4,3],[4,1],[5,3],[5,1],[5,4]] の場合下記のような graph になる。
3 は 1,2,4,5 から信頼されていて、 誰も信頼していない。 そのため、judge は 3 になる。
この graph theory の、 outdegree の辺は、 その人が他の人を信頼している数になる。
indegree の辺は他の人から信頼されている数になる。
そのため indegree と outdegree によって誰が judge か判断できる。
judge は outdegree が 0 で indegree が N - 1 となる。
trust をループして全員の indegree, outdegree の数を調査できる。
indegree = [0] * (N + 1) outdegree = [0] * (N + 1) for a, b in trust: outdegree[a] += 1 indegree[b] += 1 そして、1 ～ N 人全員をループして、チェックすれば、 judge がわかる。</description>
    </item>
    
    <item>
      <title>Invert Binary Tree</title>
      <link>https://hirotoshimizu.github.io/posts/invert-binary-tree/</link>
      <pubDate>Fri, 01 Oct 2021 11:25:38 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/invert-binary-tree/</guid>
      <description>DFS
Base Case root が Null は None を返す。
Tree を反転して値が同じなら True を返すので、
children node の値を swap して同じか確かめる。
Time complexity: O(n)
Mem complexity: O(n)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def invertTree(self, root): &amp;#34;&amp;#34;&amp;#34; :type root: TreeNode :rtype: TreeNode &amp;#34;&amp;#34;&amp;#34; if not root: return None tmp = root.</description>
    </item>
    
    <item>
      <title>Same Tree</title>
      <link>https://hirotoshimizu.github.io/posts/same-tree/</link>
      <pubDate>Fri, 01 Oct 2021 11:00:05 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/same-tree/</guid>
      <description>DFS recursive
Base Case は p,q が Null の場合同じ Tree なので return する。
もし p,q のどちらかの値が違う場合、その Tree は同じではないので、 False を return する。 また、どちらかの値が Null の場合同じ Tree ではないので、この場合も False を　return する。
Time complexity: O(n) Mem complexity: O(n)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isSameTree(self, p, q): &amp;#34;&amp;#34;&amp;#34; :type p: TreeNode :type q: TreeNode :rtype: bool &amp;#34;&amp;#34;&amp;#34; if not p and not q: return True if not p or not q or p.</description>
    </item>
    
    <item>
      <title>Maximum Depth of Binary Tree</title>
      <link>https://hirotoshimizu.github.io/posts/maximum-depth-of-binary-tree/</link>
      <pubDate>Thu, 30 Sep 2021 15:53:30 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/maximum-depth-of-binary-tree/</guid>
      <description>回答のアプローチは Recursive DFS BFS Iterative DFS
Base case root が empty children が Null
Recursive DFS
Time complexity: O(n) Mem complexity: O(n)
class Solution(object): def maxDepth(self, root): &amp;#34;&amp;#34;&amp;#34; :type root: TreeNode :rtype: int &amp;#34;&amp;#34;&amp;#34; if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) BFS
BFS を使う場合は Queue を使う。
 3  ／　＼ 9 20 ／＼ 15 7
 | 3 | 9 | 20 | 15 | 7 | 1 2 2 3 3 ← Level</description>
    </item>
    
    <item>
      <title>Lowest Common Ancestor of a Binary Search Tree</title>
      <link>https://hirotoshimizu.github.io/posts/lowest-common-ancestor-of-a-binary-search-tree/</link>
      <pubDate>Thu, 30 Sep 2021 11:08:27 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/lowest-common-ancestor-of-a-binary-search-tree/</guid>
      <description>https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
この問題の回答方法としては Recursive と Iterative なアプローチがある。
Recursive Approach
アルゴリズム
 ルートの Node から始める。 p と q が右の subtree にある場合、1から右のsubtreeを探すようにする。 p と q が左の subtree にある場合、1から左のsubtreeを探すようにする。 もし 2 と 3 のステップが not true の場合、p と q の共通の Node を見つけたこととなる。  Time complexity: O(n)
Mem complexity: O(n)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): &amp;#34;&amp;#34;&amp;#34; :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode &amp;#34;&amp;#34;&amp;#34; parent_val = root.</description>
    </item>
    
    <item>
      <title>Climbing Stairs</title>
      <link>https://hirotoshimizu.github.io/posts/climbing-stairs/</link>
      <pubDate>Sun, 26 Sep 2021 12:04:50 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/climbing-stairs/</guid>
      <description>https://leetcode.com/problems/climbing-stairs/
n = 5
 0 ／　＼ 1 2 ／＼ ／＼ 2 3 3 4 ／＼ ／＼ ／＼ ／＼ 3 4 4 5 4 5 5 6  ／＼ ／＼ ／＼　／＼ 4 5 5 6 5 6　5 6 ／＼ 5 6
n が 5 steps の場合、 8通りの選択が出来る。
DFS でも出来るかが 2^n となる。
そのため Dynamic Programming を使う。
同じ計算をする値は memoize する
 | 8 | 5 | 3 | 2 | 1 | 1 | n に辿り着くまでの数 0 1 2 3 4 5(step) one two</description>
    </item>
    
    <item>
      <title>Meeting Rooms</title>
      <link>https://hirotoshimizu.github.io/posts/meeting-rooms/</link>
      <pubDate>Sat, 25 Sep 2021 15:04:07 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/meeting-rooms/</guid>
      <description>https://leetcode.com/problems/meeting-rooms/
先ず始めに intervals のスタート時間でソートする。
intervals の時間がソートされたため、 ループで最初の会議の終わりの時間と次の会議の始まりの時間を比較し、 最初の会議の終わりの時間 が 次の会議の始まりの時間より大きい場合、 会議の時間が重なっているので、False を返す。
次の会議の開始時間 が 前の会議の終わり時間より小さい場合ループを続ける。
ループする際、次のリストと比較するため for の range で -1 をする。
ソートをするので Time complexity は O(n log n) となる。
Time complexity: O(n log n) Mem complexity: O(1)
class Solution(object): def canAttendMeetings(self, intervals): &amp;#34;&amp;#34;&amp;#34; :type intervals: List[List[int]] :rtype: bool &amp;#34;&amp;#34;&amp;#34; intervals.sort() for i in range(len(intervals) -1): if intervals[i][1] &amp;gt; intervals[i + 1][0]: return False return True </description>
    </item>
    
    <item>
      <title>Merge Two Sorted Lists</title>
      <link>https://hirotoshimizu.github.io/posts/merge-two-sorted-lists/</link>
      <pubDate>Fri, 24 Sep 2021 22:39:14 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/merge-two-sorted-lists/</guid>
      <description>https://leetcode.com/problems/merge-two-sorted-lists/
ダミー Node を作って edge case の 空の Linked List が挿入されても大丈夫なようにする。
その後はループで l1 と l2 の val を比べ、 小さい値を tail.next に入れる。 その後、 next をずらす。
ループ後 l1, l2 のどちらかのリストが empty の場合、 Linked List に追加する必要があるので、 リストが empty か確認し、値があれば Linked List に追加する。
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): &amp;#34;&amp;#34;&amp;#34; :type l1: ListNode :type l2: ListNode :rtype: ListNode &amp;#34;&amp;#34;&amp;#34; dummy = ListNode() tail = dummy while l1 and l2: if l1.</description>
    </item>
    
    <item>
      <title>Linked List Cycle</title>
      <link>https://hirotoshimizu.github.io/posts/linked-list-cycle/</link>
      <pubDate>Fri, 24 Sep 2021 21:04:07 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/linked-list-cycle/</guid>
      <description>https://leetcode.com/problems/linked-list-cycle/
Linked List が Cycle なのかを確認する。
Linked List が Cycle な場合、 2つのポインターを使う。 (1つめのポインターは 1つずつ進み、 2つめのポインターは 2つずつ進む。) Cycle な場合どこかの時点で2つ進むポインター が1つしか進まないポインターに追いつくので Cycle だとわかる。
Cycle ではない場合 いずれかの時点で ポインターが Null になる。
Time complexity: O(n) Mem complexity: O(1)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): &amp;#34;&amp;#34;&amp;#34; :type head: ListNode :rtype: bool &amp;#34;&amp;#34;&amp;#34; slow, fast = head, head while fast and fast.</description>
    </item>
    
    <item>
      <title>Reverse Linked List</title>
      <link>https://hirotoshimizu.github.io/posts/reverse-linked-list/</link>
      <pubDate>Fri, 24 Sep 2021 11:13:49 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/reverse-linked-list/</guid>
      <description>https://leetcode.com/problems/reverse-linked-list/
考え方としては、
1 → 2 → 3 → 4 → 5
1 ← 2 ← 3 ← 4 ← 5
とするように考える。
回答方法は iterative なやり方と recursive なやり方がある。 iterative なやり方は 2つの pointer を使う。
prev と curr
まず prev に　None を設定する。 curr は head にする
Null → 1 → 2 → 3 → 4 → 5 ↑ ↑ prev curr
ループしている間 Linked List の 矢印の向き (curr.next) をずらしつつ、prev と next の pointer もずらしていく。</description>
    </item>
    
    <item>
      <title>Valid Parentheses</title>
      <link>https://hirotoshimizu.github.io/posts/valid-parentheses/</link>
      <pubDate>Wed, 22 Sep 2021 20:06:14 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/valid-parentheses/</guid>
      <description>https://leetcode.com/problems/valid-parentheses/
Prerequisite Hash Map Stack
最初にどのカッコがどの 括弧閉じ にマッチしているかわかるために HashMap を作る必要がある。 この際、括弧閉じ をキーにする。
for 文で list の中を確認し、 括弧開きは stack に入れる。
stack は 最後に入れたものから出すので、 括弧開き と 括弧閉じ がマッチしていれば、 stack から pop できる。
最後に stack に何も残らなければ、 全てがマッチして True を return する。
Time complexity: O(n) Mem complexity: O(n)
class Solution(object): def isValid(self, s): &amp;#34;&amp;#34;&amp;#34; :type s: str :rtype: bool &amp;#34;&amp;#34;&amp;#34; stack = [] closeToOpen = { &amp;#39;)&amp;#39; : &amp;#39;(&amp;#39;, &amp;#39;]&amp;#39; : &amp;#39;[&amp;#39;, &amp;#39;}&amp;#39; : &amp;#39;{&amp;#39; } for c in s: if c in closeToOpen: if stack and stack[-1] == closeToOpen[c]: stack.</description>
    </item>
    
    <item>
      <title>Missing Number</title>
      <link>https://hirotoshimizu.github.io/posts/missing-number/</link>
      <pubDate>Tue, 21 Sep 2021 20:12:52 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/missing-number/</guid>
      <description>https://leetcode.com/problems/missing-number/
sum([0,1,2,3]) - sum([3,0,1]) = 2 2がない数字なので、2が残る。
最初に result に len(nums) を代入する。 nums が [3,0,1] の場合、 result に 3 が代入される。
これは for で回す時に range(len(nums)) だと 0, 1, 2 としかならないため。 result に len(nums) の代入が必要。
result += (i - nums[i]) をすることで、2 が return 出来る。
Time complexity: O(n) Mem complexity: O(1)
class Solution(object): def missingNumber(self, nums): &amp;#34;&amp;#34;&amp;#34; :type nums: List[int] :rtype: int &amp;#34;&amp;#34;&amp;#34; result = len(nums) for i in range(len(nums)): result += (i - nums[i]) return result </description>
    </item>
    
    <item>
      <title>Maximum Subarray</title>
      <link>https://hirotoshimizu.github.io/posts/maximum-subarray/</link>
      <pubDate>Tue, 21 Sep 2021 13:23:28 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/maximum-subarray/</guid>
      <description>https://leetcode.com/problems/maximum-subarray/
 | -2 | 1 | -3 | 4 | -1 | 2 | 1 | -5 | 4 | 最初の3つの合計(-2 + 1 -3)はマイナスになるので、 そのため subarray のスタートは 4 もしくは 4以降の数字になる。
合計が正の数になる場合は保持しておく。 変数に0 を代入して、 iterate しながら数字を追加していく。 合計がマイナスになる場合は保持する必要がないので、0 にする。
Time complexity: O(n) Mem complexity: O(1)
class Solution(object): def maxSubArray(self, nums): &amp;#34;&amp;#34;&amp;#34; :type nums: List[int] :rtype: int &amp;#34;&amp;#34;&amp;#34; max_subarray = nums[0] current_subarray = 0 for n in nums: if current_subarray &amp;lt; 0: current_subarray = 0 current_subarray += n max_subarray = max(max_subarray, current_subarray) return max_subarray </description>
    </item>
    
    <item>
      <title>Best Time to Buy and Sell Stock</title>
      <link>https://hirotoshimizu.github.io/posts/best-time-to-buy-and-sell-stock/</link>
      <pubDate>Tue, 21 Sep 2021 10:49:58 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/best-time-to-buy-and-sell-stock/</guid>
      <description>https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
pointer を2つ使う。 left が right より低い時点で売る可能性あり。 max_profit に最大の profit を格納。
right の pointer は右に移動し続け
left の　pointer は prices[l] が prices[r] より大きい際に、 left の pointer を right の pointer の位置に移動する。
Time complexity: O(n)
Mem complexity: O(1)
class Solution(object): def maxProfit(self, prices): &amp;#34;&amp;#34;&amp;#34; :type prices: List[int] :rtype: int &amp;#34;&amp;#34;&amp;#34; l, r = 0, 1 max_profit = 0 while r &amp;lt; len(prices): if prices[l] &amp;lt; prices[r]: profit = prices[r] - prices[l] max_profit = max(max_profit, profit) else: l = r r += 1 return max_profit </description>
    </item>
    
    <item>
      <title>Two Sum</title>
      <link>https://hirotoshimizu.github.io/posts/two-sum/</link>
      <pubDate>Tue, 21 Sep 2021 10:05:05 +0900</pubDate>
      
      <guid>https://hirotoshimizu.github.io/posts/two-sum/</guid>
      <description>https://leetcode.com/problems/two-sum/
 | 2 | 7 | 11 | 15 | 　↑　↑ 全てのコンビネーションを確認しようと Brute Force で問題を解こうとすると ループの中でループをするのでo(n^2)となる。
 | 2 | 7 | 11 | 15 | そのため HashMapを使う必要がある。 ループして array の中を確認する際に、 HashMap に val と key を持たせる。 ループ時に target - val の値が HashMap にあれば、 合計の値を持つ index が return できる。
 | 2 | 7 | 11 | 15 |  ↑   | HashMap | | val : index | | 2 : 1 |  | HashMap | | val : index | | 2 : 1 | | 7 : 2 |← | 11 : 3 | | 15 : 4 | target は 9 なので val 7 を確認時に HashMap にすでに 2 が入っているので この時点で return できる。</description>
    </item>
    
  </channel>
</rss>
