Skip to content
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

Search in Rotated Sorted Array #13

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
31 changes: 31 additions & 0 deletions pullrequests/search_in_rotated_sorted_array/step1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//lint:file-ignore U1000 Ignore all unused code
package template

/*
O(log n)で解くことを期待されていたので、何らかの形で二分探索を使うのだろうとは思っていたのですが、初見では解けなかったので、他の人の回答を参考にしました。
どちらか片方は必ず必ず昇順にならんでいるということを利用して二分探索を行っています。
下記は閉区画で解きました。
*/
func search_closed(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
mid := (left + right) / 2
if target == nums[mid] {
return mid
}
if nums[left] <= nums[mid] {
if nums[left] <= target && target < nums[mid] {
right = mid - 1
} else {
left = mid + 1
}
} else {
if nums[mid] < target && target <= nums[right] {
left = mid + 1
} else {
right = mid - 1
}
}
}
return -1
}
29 changes: 29 additions & 0 deletions pullrequests/search_in_rotated_sorted_array/step2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//lint:file-ignore U1000 Ignore all unused code
package template

/*
半閉区画でも解いてみました。
*/
func search_half_closed(nums []int, target int) int {
left, right := 0, len(nums)
for left < right {
mid := (left + right) / 2
if target == nums[mid] {
return mid
}
if nums[left] <= nums[mid] {
if nums[left] <= target && target < nums[mid] {
right = mid
} else {
left = mid + 1
}
} else {
if nums[mid] < target && target <= nums[right-1] {
left = mid + 1
} else {
right = mid
}
}
}
return -1
}