Skip to content

35. Search Insert Position#39

Open
mamo3gr wants to merge 4 commits intomainfrom
35_search-insert-position
Open

35. Search Insert Position#39
mamo3gr wants to merge 4 commits intomainfrom
35_search-insert-position

Conversation

@mamo3gr
Copy link
Owner

@mamo3gr mamo3gr commented Feb 2, 2026

問題

https://leetcode.com/problems/search-insert-position/

学習方法

標準的な進め方と同様にしている。

Step 1

  1. 5分考える
  2. 分からなかったら一度答えを見る
  3. 答えを隠して空白から書いてみて、正解になったらOK

Step 2

  1. コードを自分なりに整形する
  2. 他の人のコードとコメントを読み、それを踏まえて再整形する。正解することを確認する

Step 3

「10分以内に正解するコードが書ける」ことを確認する

(その後、レビュー依頼をする=本Pull Request)

Comment on lines +24 to +25
# target <= nums[mid] だから、midまでしか詰められなくない?と思ってしまう
last = mid - 1

Choose a reason for hiding this comment

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

docstringに閉区間と書かれており、last = len(nums) - 1という初期化なので、lastより右側のインデックスiに対してtarget <= nums[i]だと(lastのことを)捉えていることになります。

そうなると、i = midはlastより右にいないといけないのでlast = mid - 1という更新になります。


```java
class Solution {
public int searchInsert(int[] nums, int target) {

Choose a reason for hiding this comment

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

不変条件から考えられていて良いと思いました。

### 他の人のコード(つづき)

書くより読むのが大事とのことで、読みながら注釈をつけていく。
できる人は頭の中でできそうだが、自分は書きながらでないとできない。

Choose a reason for hiding this comment

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

自分は最初全然できなかったです
ただ、他の人のコードを読んだり、他の二分探索の問題を不変条件を意識しながら解いたら、ある程度できるようになりました

left_index = middle_index
else:
# target <= nums[middle_index] だから、
# rightと以降右はtarget以上

Choose a reason for hiding this comment

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

targetの時と等しい場合は早期returnがあるので、target以上ではなくtargetより大きいになりますね
どちらの解釈でもコードは変わらないし動くんですが、正確に言語化することが大事だと思ってます

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。以下で修正しました
https://github.com/mamo3gr/arai60/pull/39/changes/BASE..dc7d7523113941846336628d81725378416ebf26#r2778241496

どちらの解釈でもコードは変わらないし動くんですが、正確に言語化することが大事だと思ってます

これにとても同意です!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants