1. 程式人生 > >LeetCode33:Search in Rotated Sorted Array

LeetCode33: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

Example 2:

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

LeetCode:連結

變體:LeetCode81:Search in Rotated Sorted Array II

這題和劍指Offer_程式設計題06:旋轉陣列的最小數字(指標)

思路差不多,但是邊界處理上要難得多,我 不是很懂等號的處理==

  • 若nums[mid] == target 沒什麼好說的,返回mid
  • 若nums[mid] < target
    • 若nums[mid] < nums[right] && target <= nums[right] ||  nums[mid] > nums[right]
      • 即右邊有序且target在右邊的範圍內或者右邊非有序則 left = mid + 1
      • 因為nums[mid] < target 所以若右邊非有序,則左邊一定有序,target一定大於左邊的所有元素,只能在右邊
    • 否則right = mid – 1
  • target  < nums[mid]
    • 若nums[left] < nums[mid] && nums[left] <=target
      • 即左邊有序且target在左邊的範圍內  或者 左邊無序列  right = mid – 1;
      • 因為target  < nums[mid] ,若左邊無序則nums[mid]小於右邊的所有元素,只能在左邊。
    • 否則left = mid + 1
  • class Solution(object):
        def search(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            start = 0
            end = len(nums) - 1
            while start <= end:
                mid = (start + end) // 2
                if nums[mid] == target:
                    return mid
                elif nums[mid] >= nums[start]:
                    if target >= nums[start] and target < nums[mid]:
                        end = mid - 1
                    else:
                        start = mid + 1
                elif nums[mid] <= nums[end]:
                    if target > nums[mid] and target <= nums[end]:
                        start = mid + 1
                    else:
                        end = mid - 1
            return -1