Skip to content

155. Min Stack - #101

Open
kitano-kazuki wants to merge 1 commit into
mainfrom
155-min-stack
Open

155. Min Stack#101
kitano-kazuki wants to merge 1 commit into
mainfrom
155-min-stack

Conversation

@kitano-kazuki

Copy link
Copy Markdown
Collaborator

Comment thread memo.md

def push(self, value: int) -> None:
min_value = self.stack[-1].min_value if self.stack else float("inf")
self.stack.append(MinStackElement(value, min(min_value, value)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これ、まあいいですが、ちょっとテクニカルですね。

current_min = value
if self.stack and self.stack[-1].min_value < current_min:
    current_min = self.stack[-1].min_value
self.stack.append(MinStackElement(value, min_value))
if self.stack:
    current_min = min(self.stack[-1].min_value, value)
else:
    current_min = value
current_min = min([x.min_value for x in self.stack[-1:]] + [value])

まあ、こういうのもありますが。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1行にif文含めるのはたしかにちょっと認知負荷あがりそうですね

current_min = min([x.min_value for x in self.stack[-1:]] + [value])

この書き方は初めてみました。もしself.stack = []ならself.stack[-1:][]になるので, min([value])になるんですね。なるほど

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ruby だと safe navigation operator で

current_min = [value, stack.last&.min_value].compact.min

と書けたりします。

const currentMin = Math.min(value, ...this.stack.slice(-1).map(el => el.minValue));
const currentMin = Math.min(value, this.stack.at(-1)?.minValue ?? Infinity);

うーん。まあ、難しいですね。愚直に書くのが一番です。

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

そうですね、愚直な方法が良さそうです

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants