LeetCode – 33. Search in Rotated Sorted Array

題目連結: https://leetcode.com/problems/search-in-rotated-sorted-array/

參考解法:

https://www.youtube.com/watch?v=7SC0hWGeyBo

https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/301150/Swift-100-Beats-Logrithmic-Solution.

func search(_ nums: [Int], _ target: Int) -> Int {
    if nums.count == 0 { return -1 }
    var left = 0
    var right = nums.count - 1
    while left <= right {
        let mid = (left + right) / 2
        if nums[mid] == target {
            return mid
        } else if nums[left] <= nums[mid] {
            if target >= nums[left] && target < nums[mid] {
                right = mid - 1
            } else {
                left = mid + 1
            }
        } else {
            if target <= nums[right] && target > nums[mid] {
                left = mid + 1
            } else {
                right = mid - 1
            }
        }
    }
    return -1
}