【LeetCode每天一题】Search in Rotated Sorted Array II(在旋转数组中查找数字)

  Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

  • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
  • Would this affect the run-time complexity? How and why?

思路


       这道题在之前剑指offer中做过,两道题是一样的,都是利用二分查找的思想来进行查找,只不过这里的判断条件会复杂一些。因此我们可因此是旋转数组所以相当于会存在有序两个区间。每次进行查找时,我们先判断middle是否是target,不是时再判断nums[start] 与nums[middle]的大小关系。 然后再判断nums[start] ,nums[middle]与target的大小关系。从而可以缩小查找空间。另外因为数组中可能有重复的元素的情况,因此我们最初需要进行特殊判断是否存在,如果存在这种情况,我们只能使用顺序查找来得到结果。特殊的情况例如[0,0,0,0,0,0,-1,0,]。

图示思路


 

解决代码


 

 1 class Solution(object):
 2     def search(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: bool
 7         """
 8         if not nums:       # 空列表直接返回
 9             return False
10         start, end = 0, len(nums)-1
11         middle = start +((end - start)>>1)       # 取中间值
12         if nums[start] == nums[middle] == nums[end]:       # 异常情况
13             for i in range(end+1):
14                 if nums[i] == target:
15                     return True
16             return False
17         
18         while start <= end:           # 二分查找
19             if nums[middle] == target:
20                 return True
21             if nums[start] <= nums[middle]:          # 说明再前半部分的有序序列中
22                 if nums[start] <= target and nums[middle] > target:     # 根据情况移动指针位置
23                     end = middle -1
24                 else:
25                     start = middle + 1
26             else:                                  #  否则再后半段的有序部分
27                 if nums[end] >= target and nums[middle] < target:      
28                     start = middle +1
29                 else:
30                     end = middle - 1
31             middle = start +((end - start)>>1)       # 重新取中间值
32         return False

 

posted @ 2019-04-30 17:01  GoodRnne  阅读(243)  评论(0编辑  收藏  举报