您的位置:首页 > 编程语言 > Python开发

LeetCode 33. Search in Rotated Sorted Array

2016-11-07 09:36 267 查看
题目:

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.
题意:
在一个事先翻转的数组里面,查找一个数字,如果存在,则返回其下标,否则返回-1

题解:

看到题目难度为hard,有些不懂,直接遍历一遍就能求解,不知道是否有复杂度、空间限制

class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in range(len(nums)):
if nums[i] == target:
return i
return -1

看了下后面讨论区答案,大部分用二分法求解。 先记录下吧。

class Solution(object):
def search(self, nums, target):
left, right = 0, len(nums)-1
while right >= left:
mid = (left+right)/2
if nums[mid] == target:
return mid
# if nums[left:mid] is increasing
if nums[mid] >= nums[left]:
if nums[left] > target or nums[mid] <= target:
left = mid + 1
else:
right = mid - 1
# if nums[mid:right] is increasing
else:
if nums[right] < target or nums[mid] >= target:
right = mid - 1
else:
left = mid + 1
return -1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python leetcode