59. Leetcode 81. 搜索旋转排序数组 II(二分查找-局部有序)
生活随笔
收集整理的這篇文章主要介紹了
59. Leetcode 81. 搜索旋转排序数组 II(二分查找-局部有序)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
已知存在一個(gè)按非降序排列的整數(shù)數(shù)組 nums ,數(shù)組中的值不必互不相同。在傳遞給函數(shù)之前,nums 在預(yù)先未知的某個(gè)下標(biāo) k(0 <= k < nums.length)上進(jìn)行了 旋轉(zhuǎn) ,使數(shù)組變?yōu)?[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下標(biāo) 從 0 開始 計(jì)數(shù))。例如, [0,1,2,4,4,4,5,6,6,7] 在下標(biāo) 5 處經(jīng)旋轉(zhuǎn)后可能變?yōu)?[4,5,6,6,7,0,1,2,4,4] 。給你 旋轉(zhuǎn)后 的數(shù)組 nums 和一個(gè)整數(shù) target ,請你編寫一個(gè)函數(shù)來判斷給定的目標(biāo)值是否存在于數(shù)組中。如果 nums 中存在這個(gè)目標(biāo)值 target ,則返回 true ,否則返回 false 。你必須盡可能減少整個(gè)操作步驟。示例?1:輸入:nums = [2,5,6,0,0,1,2], target = 0
輸出:true
示例?2:輸入:nums = [2,5,6,0,0,1,2], target = 3
輸出:falseclass Solution:def search(self, nums: List[int], target: int) -> bool:l,r = 0,len(nums)-1while l <= r:mid = l + (r-l)//2if nums[mid] == target:return Truewhile l < mid and nums[l] == nums[mid]:l += 1if nums[l] <= nums[mid]:if nums[l] <= target < nums[mid]:r = mid - 1else:l = mid + 1else:if nums[mid] < target <= nums[r]:l = mid + 1else:r = mid - 1return False
總結(jié)
以上是生活随笔為你收集整理的59. Leetcode 81. 搜索旋转排序数组 II(二分查找-局部有序)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 57. Leetcode 257. 二叉
- 下一篇: 60. Leetcode 面试题 10.