zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第81题:假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。 编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。

    题目:
    假设按照升序排序的数组在预先未知的某个点上进行了旋转。  ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。  编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。

    进阶:

    • 这是 搜索旋转排序数组 的延伸题目,本题中的 nums  可能包含重复元素。
    • 这会影响到程序的时间复杂度吗?会有怎样的影响,为什么?

    思路:

    节省空间使用二分法。

    程序:

    class Solution:
        def search(self, nums: List[int], target: int) -> bool:
            length = len(nums)
            if length <= 1:
                if target in nums:
                    return True
                else:
                    return False
            head = 0
            tail = length - 1
            while head <= tail:
                middle = (head + tail) // 2
                if nums[middle] == target:
                    return True
                if nums[head] == nums[middle] and nums[middle] == nums[tail]:
                    head += 1
                    tail -= 1
                elif nums[head] > nums[middle]:
                    if target > nums[middle] and target <= nums[tail]:
                        head = middle + 1
                    else:
                        tail = middle - 1
                else: #nums[head] <= nums[middle]:
                    if target >= nums[head] and target < nums[middle]:
                        tail = middle - 1
                    else:
                        head = middle + 1
            return False
  • 相关阅读:
    HDU 5583 Kingdom of Black and White 水题
    HDU 5578 Friendship of Frog 水题
    Codeforces Round #190 (Div. 2) E. Ciel the Commander 点分治
    hdu 5594 ZYB's Prime 最大流
    hdu 5593 ZYB's Tree 树形dp
    hdu 5592 ZYB's Game 树状数组
    hdu 5591 ZYB's Game 博弈论
    HDU 5590 ZYB's Biology 水题
    cdoj 1256 昊昊爱运动 预处理/前缀和
    cdoj 1255 斓少摘苹果 贪心
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12761611.html
Copyright © 2011-2022 走看看