分析:已經排好序了,With binary search the most appropriate
def search_range(arr, low, high, key):
out = [-1, -1]
mid = (low+high) // 2
if low == high & key != arr[low]:
return [-1, -1]
if key == arr[mid]:
for i in range(mid, high): # range()左閉右開
if key == arr[i]:
out[1] = i
j = mid
while arr[j] == key:
out[0] = j
j = j - 1
return out
elif key < arr[mid]:
temp_high = mid
return search_range(arr, low=low, high=temp_high, key=key)
else:
temp_low = mid + 1
return search_range(arr, low=temp_low, high=high, key=key)
if __name__ == '__main__':
list1 = [5, 7, 7, 8, 8, 10, 10]
print(search_range(list1, low=0, high=len(list1), key=10))
Given a sorted array and a target,如果找到了目標,則返回索引.如果沒有,則返回索引 If order insert,It returns its index.You can assume that the array no repeat things
.
方法一
:循環遍歷,這裡不再贅述.方法二
:先排序,Then return the value of insert index
def searchInsert(nums, target):
if target not in nums:
nums.append(target) # 末尾追加
nums.sort() # 排序
return nums.index(target) # 返回索引
方法三
:二叉搜索(推薦)
def search_insert(nums, low, high, key):
if low == high:
return low
mid = (high + low) // 2
if nums[mid] < key:
temp_low = mid + 1
return search_insert(nums, low=temp_low, high=high, key=key)
elif nums[mid] > key:
temp_high = mid
return search_insert(nums, low=low, high=temp_high, key=key)
else: # nums[mid] == key
return mid
if __name__ == '__main__':
list1 = [1, 3, 5, 7, 8, 10]
print(search_insert(list1, low=0, high=len(list1), key=9))
Write an effective algorithm,在一個m×n
The matrix of searches for a value.The matrix has the following features.
例如,The following matrix.
[[1,3,5,7],
[10,11,16,20],
[23,30,34,50]]
解法一
:使用numpyThe 2 d array into a one-dimensional array,Then use the binary search
def search_2dm(matrix_flatten, low, high, target):
if low >= high and matrix_flatten[low] != target: # 沒有key值
return False
mid = (high + low) // 2
if matrix_flatten[mid] > target:
temp_high = mid
return search_2dm(matrix_flatten, low=low, high=temp_high, target=target)
elif matrix_flatten[mid] < target:
temp_low = mid + 1
return search_2dm(matrix_flatten, low=temp_low, high=high, target=target)
else: # matrix_flatten[mid] == key
return True
if __name__ == '__main__':
list1 = [[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]]
list1 = np.array(list1).flatten()
print(search_2dm(list1, low=0, high=len(list1), target=2))
方法二
:
def search_matrix(matrix, target):
matrix = np.array(matrix)
row = matrix.shape[0] # 獲取行號
column = matrix.shape[1] # 獲取列數
first = 0
last = row * column
while first < last:
mid = first + (last-first)//2
value = matrix[(mid // column), (mid % column)]
if value == target:
return True
elif value < target:
first = mid + 1
else:
last = mid
return False
if __name__ == '__main__':
list1 = [[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]]
print(search_matrix(list1, 70))