Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 9c660e6

Browse files
committed
33 重构了程序,添加了更详细的代码
1 parent 715ea79 commit 9c660e6

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

Algorithms/0033.search-in-rotated-sorted-array/search-in-rotated-sorted-array.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
package problem0033
22

33
func search(nums []int, target int) int {
4+
rotated := indexOfMin(nums) /* 数组旋转了的距离 */
45
size := len(nums)
56
left, right := 0, size-1
6-
/* 数组旋转了的距离 */
7-
rotated := indexOfMin(nums)
87

98
for left <= right {
109
mid := (left + right) / 2
1110
/* nums 是 rotated,所以需要使用 rotatedMid 来获取 mid 的值 */
1211
rotatedMid := (rotated + mid) % size
1312
switch {
14-
case nums[rotatedMid] > target:
15-
right = mid - 1
1613
case nums[rotatedMid] < target:
1714
left = mid + 1
15+
case target < nums[rotatedMid]:
16+
right = mid - 1
1817
default:
1918
return rotatedMid
2019
}
@@ -29,7 +28,7 @@ func indexOfMin(nums []int) int {
2928
left, right := 0, size-1
3029
for left < right {
3130
mid := (left + right) / 2
32-
if nums[mid] > nums[right] {
31+
if nums[right] < nums[mid] {
3332
left = mid + 1
3433
} else {
3534
right = mid

Algorithms/0033.search-in-rotated-sorted-array/search-in-rotated-sorted-array_test.go

+18-7
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,26 @@ func Test_Problem0033(t *testing.T) {
8181
}
8282
}
8383

84-
func Test_indexOfMin(t *testing.T) {
84+
func Test_indexOfMin_evenLength(t *testing.T) {
8585
ast := assert.New(t)
86-
8786
array := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
88-
87+
numsSize := 10
8988
for i := 0; i < 10; i++ {
90-
nums := array[i : i+10]
91-
actual := 9 - i
92-
expected := indexOfMin(nums)
93-
ast.Equal(expected, actual)
89+
nums := array[i : i+numsSize]
90+
indexOfZeroInNums := 9 - i
91+
actual := indexOfMin(nums)
92+
ast.Equal(indexOfZeroInNums, actual)
93+
}
94+
}
95+
96+
func Test_indexOfMin_oddLength(t *testing.T) {
97+
ast := assert.New(t)
98+
array := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
99+
numsSize := 9
100+
for i := 1; i < 10; i++ {
101+
nums := array[i : i+numsSize]
102+
indexOfZeroInNums := 9 - i
103+
actual := indexOfMin(nums)
104+
ast.Equal(indexOfZeroInNums, actual)
94105
}
95106
}

0 commit comments

Comments
 (0)