美文网首页leetcode
81. Search in Rotated Sorted Arr

81. Search in Rotated Sorted Arr

作者: AnakinSun | 来源:发表于2019-03-24 20:54 被阅读0次

二分查找

func search(nums []int, target int) bool {
    l := len(nums)
    if l == 0 {
        return false
    }
    left, right := 0, l-1
    for left <= right {
        mid := left + (right-left)/2
        if nums[mid] == target {
            return true
        } else if nums[mid] < nums[right] {
            if nums[mid] < target && nums[right] >= target {
                left = mid + 1
            } else {
                right = mid - 1
            }
        } else if nums[mid] > nums[right] {
            if nums[left] <= target && nums[mid] > target {
                right = mid - 1
            } else {
                left = mid + 1
            }
        } else {
            right--
        }

    }
    return false
}

相关文章

网友评论

    本文标题:81. Search in Rotated Sorted Arr

    本文链接:https://www.haomeiwen.com/subject/qdjpvqtx.html