![[leetcode] Find Minimum in Rotated Sorted Array II,第1张 [leetcode] Find Minimum in Rotated Sorted Array II,第1张](/aiimages/%5Bleetcode%5D+Find+Minimum+in+Rotated+Sorted+Array+II.png)
code:https://play.golang.org/p/luj1fdu03F
problem: https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
package mainimport ( "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数组方法2func 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] }} 总结 以上是内存溢出为你收集整理的[leetcode] Find Minimum in Rotated Sorted Array II全部内容,希望文章能够帮你解决[leetcode] Find Minimum in Rotated Sorted Array II所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)