LeetCode 704 二分查找

给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target  ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1
示例 1:

输入: nums= [-1,0,3,5,9,12], target= 9输出: 4

解释: 9 出现在 nums中并且下标为 4

示例 2:

输入: nums= [-1,0,3,5,9,12], target= 2输出: -1
解释: 2 不存在 nums中因此返回 -1

提示:

  1. 你可以假设 nums 中的所有元素是不重复的。
  2. n 将在 [1, 10000]之间。
  3. nums 的每个元素都将在 [-9999, 9999]之间。
class Solution:
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target in nums:
            index = nums.index(target)
            return index
        else:
            return -1


s1 = Solution()
print(s1.search([-1,0,3,5,9,12],9))
print(s1.search([-1,0,3,5,9,12],2))

我是不是没有领悟题目精髓.....

冒泡写法:

class Solution:
    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
        else:
            return -1


s1 = Solution()
print(s1.search([-1,0,3,5,9,12],9))
print(s1.search([-1,0,3,5,9,12],2))

猜你喜欢

转载自blog.csdn.net/Spencer_q/article/details/82017113
今日推荐