ninehills / blog

https://ninehills.tech
862 stars 80 forks source link

LeetCode-33. Search in Rotated Sorted Array #49

Closed ninehills closed 7 years ago

ninehills commented 7 years ago

问题

https://leetcode.com/problems/search-in-rotated-sorted-array/description/ Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

思路

解答

package main

import "fmt"

// ----------------------
func search(nums []int, target int) int {
    var l int = 0
    var r int = len(nums) - 1
    if r < 0 {
        return -1
    }
    for l < r {
        m := (l + r) / 2
        if nums[m] == target {
            return m
        }
        if nums[m] >= nums[l] {
            if target < nums[m] && target >= nums[l] {
                r = m - 1
            } else {
                l = m + 1
            }
        } else {
            if target > nums[m] && target <= nums[r]{
                l = m + 1
            } else {
                r = m - 1
            }
        }
    }
    if nums[l] == target {
        return l
    } else {
        return -1
    }
}

// ----------------------

func main() {
    fmt.Println(search([]int{1, 3}, 0))
    fmt.Println(search([]int{}, 5))
    fmt.Println(search([]int{4, 5, 6, 7, 0, 1, 2}, 1))
    fmt.Println(search([]int{4, 5, 6, 7, 8, 1, 2, 3}, 8))
}
ninehills commented 7 years ago

4