-
Couldn't load subscription status.
- Fork 0
Solved Arai60/33. Search in Rotated Sorted Array #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| index = binary_search_from_left(nums, target, key=score_num) | ||
| if nums[index] == target: | ||
| return index | ||
| return -1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
面白い書き方だと思いました。
num > nums[-1]はnum >= nums[0]としても動きますかね?
個人的にはscore_numは次のように書いてしまえば初見でもわかりやすくなるかもしれないと思いました。(今の書き方もエレガントで面白いですが)
if target > nums[-1]:
if num >= target or num <= nums[-1]:
return 1
if target <= nums[-1]:
if num >= target and num <= nums[-1]:
return 1
return 0There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
もしこうするならscore_numはis_past_targetみたいな名前のbooleanを返す関数にしてしまって、
if key(nums[middle]) < key(target)みたいなところはif not is_past_target(num)みたいな形にしてもいいかもしれません。
| class Solution: | ||
| def search(self, nums: List[int], target: int) -> int: | ||
| def score_num(num: int) -> int: | ||
| return -(num > nums[-1]) + (num >= target) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ブール値を足すことに私は抵抗があります
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ドキュメントにも書かれてました。初めて知りました。
https://docs.python.org/3/library/stdtypes.html#typebool
In many numeric contexts, False and True behave like the integers 0 and 1, respectively. However, relying on this is discouraged; explicitly convert using int() instead.
| left = middle | ||
| continue | ||
| return -1 | ||
| return left |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
私の理解不足かもしれませんが、left = 0, middle = 0 となった時に is_between の right-1 は -1 になり、結果的に正しく動いているように見えて不思議に思いました。
| class Solution: | ||
| def search(self, nums: List[int], target: int) -> int: | ||
| def score_position(num: int) -> int: | ||
| return (num <= nums[-1]) + (num >= target) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(num <= nums[-1], num) で本当はいいみたいですね。
問題文:https://leetcode.com/problems/search-in-rotated-sorted-array/description/