81. Search in Rotated Sorted Array II
https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
js
/**
* @param {number[]} nums
* @param {number} target
* @return {boolean}
*/
var search = function(nums, target) {
if (!nums.length) {
return -1
}
var l = 0
var r = nums.length - 1
while (l <= r) {
let m = (l + r) / 2 >> 0
if (nums[m] === target) {
return true
}
let inLeft = nums[m] > nums[l] && target >= nums[l] && target < nums[m]
let notInRight = nums[m] < nums[l] && !(target <= nums[r] && target > nums[m])
if (inLeft || notInRight) {
r = m - 1
} else if (nums[m] === nums[l]) {
l++
} else {
l = m + 1
}
}
return false
}
py
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
if not nums:
return -1
l, r = 0, len(nums) - 1
while l <= r:
m = (l + r) // 2
if nums[m] == target:
return True
inLeft = nums[m] > nums[l] and target >= nums[l] and target < nums[m]
notInRight = nums[m] < nums[l] and not(target <= nums[r] and target > nums[m])
if inLeft or notInRight:
r = m - 1
elif nums[m] == nums[l]:
l += 1
else:
l = m + 1
return False