标签:
题目来源
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之后的值的,所以在二分的时候利用好这个信息就好了
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
[LeetCode]题解(python):033-Search in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/loadofleaf/p/5004435.html