比较简单,直接二分查找实现就行,但是也可以借助python的list.index函数直接实现。

# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 10:45:58 2022

@author: Administrator
"""
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param nums int整型一维数组 
# @param target int整型 
# @return int整型
#
import math

class Solution:
    def search1(self , nums, target: int) -> int:
        # write code here
        try:
            index = nums.index(target)
            return index
        except:
            return -1
    def search(self , nums, target: int) -> int:
        if len(nums) == 0:
            return -1
        first = 0 ; last = len(nums)-1
        if target == nums[first]:
            return first
        elif target == nums[last]:
            return last
        elif target < nums[first]:
            return -1
        elif target > nums[last]:
            return -1
        while True:
            mid = int((first+last)/2)
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                last = mid
            elif nums[mid] < target:
                first = mid
            if first>=last-1:
                return -1


x = [1,2,3,4,5]
print(Solution().search(x,2))