Leetcode - Edit Distance
Leetcode - Search in Rotated Sorted Array II

Leetcode - Search in Rotated Sorted Array

violet posted @ Mar 23, 2020 07:22:28 AM in 算法 with tags Algorithm Golang BinarySearch , 213 阅读

https://leetcode.com/problems/search-in-rotated-sorted-array/

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.

Your algorithm's runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

 

func search(nums []int, target int) int {
    left := 0
    right := len(nums)-1
    var mid int
    for left <= right {
        mid = (left+right)/2
        if nums[mid] == target {
            return mid
        }
        if nums[mid] <= nums[right] {//pivot is on left side
            if target > nums[mid] && target <= nums[right] {
                left = mid + 1
            } else {
                right = mid - 1
            }
        } else { // pivot is on right side
            if target >= nums[left] && target < nums[mid] {
                right = mid - 1
            } else {
                left = mid + 1
            }
        }
    }
    return -1
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter