leetcode33 Search in Rotated Sorted Array

 1 """
 2 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
 3 (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
 4 You are given a target value to search. If found in the array return its index, otherwise return -1.
 5 You may assume no duplicate exists in the array.
 6 Your algorithm's runtime complexity must be in the order of O(log n).
 7 Example 1:
 8 Input: nums = [4,5,6,7,0,1,2], target = 0
 9 Output: 4
10 Example 2:
11 Input: nums = [4,5,6,7,0,1,2], target = 3
12 Output: -1
13 """
14 """
15 题目要求时间复杂度为O(log n)
16 先不管这个要求。AC混一下
17 得到解法一
18 """
19 class Solution1:
20     def search(self, nums, target):
21         if target not in nums:
22             return -1
23         for i in range(len(nums)):
24             if nums[i] == target:
25                 return i
26 
27 """
28 真正的解法是二分法
29 主要分两种情况:
30     若nums[left]<=nums[mid],这说明前半部分是排序的
31     若nums[left]<=target<=nums[mid],在前半部分搜索,反之在后半部分搜索
32     若nums[left]>nums[mid],这说明后半部分是排序的
33     若nums[mid]<=target<=nums[right],在后半部分搜索,反之在前半部分搜索
34     一直搜索,直到left>=right
35 传送门:https://www.jianshu.com/p/7295418b260f
36 """
37 class Solution2:
38     def search(self, nums, target):
39         n = len(nums)
40         left, right = 0, n-1
41         while left < right:
42             mid = (left+right)//2
43             if nums[mid] == target:
44                 return mid
45             if nums[left] <= nums[mid]: #前办部分有序
46                 if nums[left] <= target <= nums[mid]:
47                     right = mid
48                 else:
49                     left = mid + 1
50             else:#后半部分有序
51                 if nums[mid] <= target <= nums[right]:
52                     left = mid + 1
53                 else:
54                     right = mid
55         return left if nums and nums[left] == target else -1

 

posted @ 2020-02-12 22:33  yawenw  阅读(105)  评论(0编辑  收藏  举报