Skip to content

Commit b43c88b

Browse files
aQuaaQua
aQua
authored and
aQua
committed
finish Problem 33
想通了以后,就会觉得题目好简单。
1 parent eabc11a commit b43c88b

File tree

2 files changed

+23
-12
lines changed

2 files changed

+23
-12
lines changed

Algorithms/0033.search-in-rotated-sorted-array/README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,19 @@ You are given a target value to search. If found in the array return its index,
1010
You may assume no duplicate exists in the array.
1111

1212
## 解题思路
13+
先假设old = [0, 1, 2, 4, 5, 6, 7],利用二分查找法,很容易可以`5`的索引号,当old变换成了new = [4, 5, 6, 7, 0, 1, 2]以后,同样可以使用二分查找法,因为old和new中的元素有明确的对应关系
1314

15+
old[i] == new[j],只要i和j满足关系式
16+
```go
17+
j=i+4
18+
if j > len(old) {
19+
j -= len(old)
20+
}
21+
```
22+
其中,4 = old中的最大值在new中的索引号 + 1
1423

15-
## 总结
24+
所以,如果我们手中只有new,我们可以假装自己还是在对old使用二分查找法,当需要获取old[i]的值进行比较判断的时候,使用new[j]的值替代即可。
1625

1726

27+
## 总结
28+
本题是二分查找法的升级版

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

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,33 @@ package Problem0033
22

33
func search(nums []int, target int) int {
44
var index, indexOfMax int
5-
65
length := len(nums)
76

87
if length == 0 {
98
return -1
109
}
1110

11+
// 获取最大值的索引号,以便进行索引号变换
1212
for indexOfMax+1 < length && nums[indexOfMax] < nums[indexOfMax+1] {
1313
indexOfMax++
1414
}
1515

16-
lo, hi, median := 0, length-1, 0
17-
for lo <= hi {
18-
median = (lo + hi) / 2
16+
low, high, median := 0, length-1, 0
17+
for low <= high {
18+
median = (low + high) / 2
1919

20-
relativeIndex := median + indexOfMax + 1
21-
if relativeIndex < length {
22-
index = relativeIndex
23-
} else {
24-
index = relativeIndex - length
20+
// 变换索引号
21+
index = median + indexOfMax + 1
22+
if index >= length {
23+
index -= length
2524
}
2625

26+
// 传统二分查找法的比较判断
2727
switch {
2828
case nums[index] > target:
29-
hi = median - 1
29+
high = median - 1
3030
case nums[index] < target:
31-
lo = median + 1
31+
low = median + 1
3232
default:
3333
return index
3434
}

0 commit comments

Comments
 (0)