[LeetCode]题解(python):033-Search in Rotated Sorted Array


题目来源


https://leetcode.com/problems/search-in-rotated-sorted-array/

Suppose a sorted array 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.


题意分析


Input: a list with rotated sorted array with a unknown pivot

Output:index or -1

Conditions:在一个翻转数组中,找到target的位置,若不能找到则返回-1


题目思路


此题是关于二分查找的题目, 关键在于确定二分的位置,注意到数组仅是关于一个pivot位置的翻转,意味着这个pivot之前的值都是大于pivot之后的值的,所以在二分的时候利用好这个信息就好了

  1. 用first和last存储首尾位置,mid = (first + mid)// 2;
  2. 如果target等于nums[mid],返回target值;
  3. 如果nums[first] < nums[mid]:
  4. 如果nums[first] >= nums[mid]
  5. 对3,4两种条件,加上target与nums[mid]的值的比较,与target与nums[first]的比较,则可确定新的first与last的范围

AC代码(Python)


 1 class Solution(object):
 2     def search(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         size = len(nums)
 9         first = 0
10         last = size
11         while first < last:
12 
13             mid = (last + first) // 2
14             print(first,mid, last)
15             if nums[mid] == target:
16                 return mid
17             elif nums[first] <= nums[mid]:
18                 if target <= nums[mid] and target >= nums[first]:
19                     last = mid
20                 else:
21                     first = mid + 1
22             else:
23                 if target > nums[mid] and target < nums[first]:
24                     first = mid + 1
25                 else:
26                     last = mid
27 
28 
29 
30         return -1
View Code

 

posted @ 2015-11-29 11:03  loadofleaf  Views(149)  Comments(0Edit  收藏  举报