Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added 35-search-insert-position/.DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions 35-search-insert-position/problem.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## 問題: [35. Search Insert Position](https://leetcode.com/problems/search-insert-position/description/)
22 changes: 22 additions & 0 deletions 35-search-insert-position/step1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Step 1

- 二分探索で解く

```python
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start_index, end_index = 0, len(nums) - 1
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

原則 1 行に 1 つの代入文を書いたほうが、読み手にとって読みやすくなると思います。 swap をする場合は例外だと思います。

while start_index <= end_index:
middle_index = (start_index + end_index) // 2
if nums[middle_index] == target:
return middle_index
Comment on lines +11 to +12
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この部分はあってももちろんいいんですが,ない方が多くの標準ライブラリにある二分探索の実装に近いですね.
目的に応じて使い分けると良いと思います,今回は問題制約から重複がないことがわかっているので,どちらでも良いでしょう.

elif nums[middle_index] < target:
start_index = middle_index + 1
else:
end_index = middle_index - 1
return start_index
```

時間計算量: $O(\log n)$

空間計算量: $O(1)$
16 changes: 16 additions & 0 deletions 35-search-insert-position/step2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Step 2

```python
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start, end = 0, len(nums) - 1
while start <= end:
middle = start + (end - start) // 2
if nums[middle] == target:
return middle
elif nums[middle] < target:
start = middle + 1
else:
end = middle - 1
return start
```
22 changes: 22 additions & 0 deletions 35-search-insert-position/step3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Step 3

```python
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start, end = 0, len(nums) - 1
while start <= end:
middle = start + (end - start) // 2
if nums[middle] == target:
return middle
elif nums[middle] > target:
end = middle - 1
else:
start = middle + 1
return start
```

1回目: 1分 31秒

2回目: 1分 26秒

3回目: 1分 27秒