Min Stack

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) -> None: self.stack.append(x) if not self.min_stack or x <= self.min_stack[-1]: self.min_stack.append(x) def pop(self) -> None: if self.min_stack[-1] == self.stack[-1]: self.min_stack.pop() self....

October 20, 2021

Valid Anagram

anagram かどうかを調べるには s, t の出現する文字のカウントが同じなら anagram と言える。 回答方法は 文字数をカウントし、s と t を比較する 文字数をカウントし、s と t を比較する(Counter を使う) sorted を使う Input: s = “anagram”, t = “nagaram” 文字数をカウントし、s と t を比較する class Solution: def isAnagram(self, s: str, t: str) -> 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] !...

October 20, 2021

Happy Number

パターン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...

October 20, 2021

Replace Elements With Greatest Element on Right Side

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]) -> 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

October 18, 2021

Palindrome Linked List

この問題の解き方は 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...

October 18, 2021