标签:binary class print break arc ISE array script self
Topic: Binary Search
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Example
For [4, 5, 1, 2, 3] and target=1, return 2.
For [4, 5, 1, 2, 3] and target=0, return -1.
Challenge
O(logN) time
class Solution:
def search(self, A: ‘List[int]‘, target: ‘int‘) -> ‘int‘:
# write your code here
if A == []:
return -1
l = 0
r = len(A)-1#注意!
f = -1 # breakpoint
while(l<=r):
m = (l + r) // 2
#print(l,m,r)
if A[m]>A[0]:
l = m+1
else:
#1. m == 0
#2. m == len(A)-1 ok
# 不存在需要m==0的情况
# if m == 0:
# f = -1
# break
if m == 0:
if len(A)==1:
f = -1
else:
if A[0]>A[1]:
f = 1
else:
f = -1
break
if A[m-1]>A[m]:#注意向下取整
f = m
break
else:
r = m-1
#print(f)
if f == -1:
l = 0
r = len(A) - 1
else:
if target>=A[0]:
l = 0
r = f-1
else:
l = f
r = len(A)-1
while(l<=r):
m = (l+r)//2
if A[m] == target:
return m
else:
if A[m]>target:
r = m-1
else:
l = m+1
return -1
class Solution:
# @param {integer[]} numss
# @param {integer} target
# @return {integer}
def search(self, nums, target):
if not nums:
return -1
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) / 2
if target == nums[mid]:
return mid
if nums[low] <= nums[mid]:
if nums[low] <= target <= nums[mid]:
high = mid - 1
else:
low = mid + 1
else:
if nums[mid] <= target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
情况比较多,在处理边界问题上频繁出错。
应该考虑
气死我了,看看人家的思路多好!我真是脑残。
同类问题[Leetcode]81. Search in Rotated Sorted Array II
[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array
标签:binary class print break arc ISE array script self
原文地址:https://www.cnblogs.com/siriusli/p/10357071.html