-
Notifications
You must be signed in to change notification settings - Fork 0
33. Search in Rotated Sorted Array #41
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
#### 2c | ||
- 2bと同じロジックを構造体を使って実装 | ||
- numsの尻より大きいか -> targetとの大小比較 の順に調べる | ||
- https://github.com/Yoshiki-Iwasa/Arai60/pull/36/files#r1712955053 |
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.
見直したら cmp いらなくて
def priority(x):
return (x <= nums[-1], target <= x)
これでよかったです。ただ、Go で書くと少し面倒ですね。
良いと思いました。 |
tail := nums[len(nums)-1] | ||
isTargetLargerThanTail := target > tail | ||
for left < right { | ||
middle := left + (right-left)/2 |
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.
ここで
if nums[middle] == target {
return middle
}
のようにするのはどうでしょうか。
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.
ありがとうございます。こちらでの指摘も含めて違う書き方ができますね。今回の問題ではnumsに重複要素が含まれないことが保証されていますが、そうでない場合はtargetに一致する要素のうちランダムなものが返ることに注意ですね。
} else { | ||
right = middle | ||
} | ||
continue |
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.
ここは好みかと思うのですが、私はif-elseにした方が好きです。
ちなみに上でアーリーリターンしておけばright = middle - 1
とできると思います。
としてnumsを[false,...,false,true,...,true]のような配列とみなした時、 | ||
一番左のtrueの位置を探す問題と捉える | ||
- nums=[6,0,2,4], target=2 -> [false,false,true,true] | ||
- nums=[6,0,2,4], target=1 -> [false,false,false,false] |
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.
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.
おっしゃる通りですね。
T/F を target 以上の nums の要素のうち最小のものとそれより右のもの、と定義した方がいいですかね。
nums=[6,0,2,4], target=2 -> [false, false, true, true]
nums=[6,0,2,4], target=1 -> [false, false, true, true]
nums=[6,0,2,4], target=5 -> [true, true, true, true]
https://leetcode.com/problems/search-in-rotated-sorted-array/description/