lc33. Search in Rotated Sorted Array

123 阅读1分钟
  1. Search in Rotated Sorted Array Medium

3410

386

Add to List

Share 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

思路:时间复杂度为O(log n),用二分查找 先判断左边,右边哪边有序 有序的一边是否包含target,包含,l=mid+1 or r=mid-1

代码:python3

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if not nums:
            return -1   
        if len(nums)==1:
            if target==nums[0]:
                return 0
            else:
                return -1
        i=0
        j=len(nums)-1
        while i<j:
            mid = (i+j)//2
            print(mid)
            if nums[i]==target:
                return i
            if nums[j]==target:
                return j
            if nums[mid]==target:
            	return mid
            if nums[i]<nums[mid]:
                if nums[i]<target and nums[mid]>target:
                    j=mid-1
                else:
                    i=mid+1
                print(str(i)+"#"+str(j))
            else:
                if nums[j]>target and nums[mid]<target:
                    i=mid+1
                else:
                    j=mid-1
                print(str(i)+"*"+str(j))

        return -1