Leetcode - Search in Rotated Sorted Array
Leetcode - Find the Duplicate Number

Leetcode - Search in Rotated Sorted Array II

violet posted @ Mar 23, 2020 07:24:16 AM in 算法 with tags Algorithm Golang BinarySearch , 199 阅读

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

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

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

 

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

    return false
}

 

 


登录 *


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