LeetCode 33. Search in Rotated Sorted Array

来源:互联网 发布:河北seo按效果付费 编辑:程序博客网 时间:2024/06/06 08:29

题目:

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


0 0
原创粉丝点击