1. 程式人生 > >【LeetCode】81. Search in Rotated Sorted Array II 解題報告(Python)

【LeetCode】81. Search in Rotated Sorted Array II 解題報告(Python)

題目描述:

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

  • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
  • Would this affect the run-time complexity? How and why?

題目大意

在一個含有重複數字的旋轉遞增陣列中,找出是否存在某個數字。

解題方法

這樣的話,如果直接進行左右指標的比較就不知道向哪個方向搜尋了,所以,需要在正式比較之前,先移動左指標,是他指向一個和右指標不同的數字上。然後再做33題的查詢。

至於查詢部分,可以這麼考慮:首先nums[l] > num[r]認為是恆成立的。

如果mid指向的位置比nums[l]還大,那麼說明l到mid是有序的,這個時候如果nums[l] <= target < nums[mid]說明要查詢的在Mid前面,移動右指標;否則要查詢的在mid後面,移動左指標。

如果mid指向的位置比nums[r]還小,那麼說明mid到r是有序的,然後同樣的進行比較操作就行了。

時間複雜度是O(N),空間複雜度是O(1).

class Solution(object):
    def search(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: bool
        """
N = len(nums) l, r = 0, N - 1 while l <= r: while l < r and nums[l] == nums[r]: l += 1 mid = l + (r - l) / 2 if nums[mid] == target: return True if nums[mid] >= nums[l]: if nums[l] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 elif nums[mid] <= nums[r]: if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid - 1 return False

參考資料

日期

2018 年 10 月 20 日 —— 10月剩餘的時間又不多了