mycode

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target in nums:
            return nums.index(target)
        else:
            return -1

 

参考:

二分查找

可以和34 Search for a Range对比思考,都是采用二分法哦!

class Solution:
    # @param {integer[]} numss
    # @param {integer} target
    # @return {integer}
    def search(self,nums,target):
        if not nums:
            return -1
        low,high=0,len(nums)-1
        while low<=high:
            mid=(low+high)/2
            if target==nums[mid]:
                return mid
            if nums[low]<=nums[mid]:
                if nums[low]<=target<=nums[mid]:
                    high=mid-1
                else:
                    low=mid+1
            else:
                if nums[mid]<=target<=nums[high]:
                    low=mid+1
                else:
                    high=mid-1
        return -1