code:https://play.golang.org/p/luj1fdu03F
problem: https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"fmt"
"math/rand"
"sort"
"time"
)
//rotate数组方法一
func rotateArray1(a []int, pos int) {
if pos < 0 {
return
}
lenA := len(a)
pos = pos % lenA
tmpArray := make([]int, pos)
for i := 0; i < pos; i++ {
tmpArray[i] = a[i]
}
for i := pos; i < lenA; i++ {
a[i-pos] = a[i]
}
for i := 0; i < pos; i++ {
a[lenA-pos+i] = tmpArray[i]
}
}
//rotate数组方法2
func rotateArray2(a []int, pos int) {
if pos < 0 {
return
}
lenA := len(a)
pos = pos % lenA
reverseArray(a[:pos])
reverseArray(a[pos:])
reverseArray(a)
}
//reverse数组,反转
func reverseArray(a []int) {
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
}
func main() {
len := 20
a := make([]int, len)
seedNum := 0
rand.Seed(int64(seedNum) + time.Now().UnixNano())
for i := 0; i < len; i++ {
seedNum++
a[i] = rand.Intn(20)
}
fmt.Println("-------")
sort.Ints(a)
rotatePos := rand.Intn(len)
fmt.Printf("rotate pos:%d\n", rotatePos)
fmt.Printf("origin array:%v\n", a)
rotateArray2(a, rotatePos)
fmt.Printf("rotated array:%v\n", a)
//sort.Sort(sort.Reverse(sort.IntSlice(a[])))
fmt.Println(findMin(a))
}
func findMin(arrItem []int) int {
lenItem := len(arrItem)
low := 0
high := lenItem - 1
if arrItem[low] < arrItem[high] {
return arrItem[low]
}
for low < high-1 {
mid := (low + high) / 2
if arrItem[low] >= arrItem[high] {
if arrItem[mid] < arrItem[low] {
high = mid
} else {
low = mid
}
}
}
if arrItem[low] < arrItem[high] {
return arrItem[low]
} else {
return arrItem[high]
}
}