获取绝对值最小
代码:
def getAbsNumber(arr: list) -> int:
if arr[0] >= 0:
return arr[0]
elif arr[-1] <= 0:
return abs(arr[-1])
else:
low, high = 0, len(arr)-1
while True:
mid = (low+high)//2
if arr[mid] >= 0 and arr[mid-1] < 0:
if abs(arr[mid]) < abs(arr[mid-1]):
return arr[mid]
else:
return arr[mid-1]
elif arr[mid] > 0:
high = mid
elif arr[mid] < 0:
low = mid
def getAbsNumber2(arr: list) ->int:
minNumber = abs(arr[0])
for i in arr[1:]:
if abs(minNumber)>abs(i):
minNumber=abs(i)
return minNumber
if __name__ == "__main__":
arrayList01 = [0, 5, 6, 9, 10]
arrayList02 = [-8, -6, -5, -3, -2, -1]
arrayList03 = [-8, -6, -5, -3, -2, -1, 0, 5, 6, 9, 10]
print(getAbsNumber(arrayList01))
print(getAbsNumber(arrayList02))
print(getAbsNumber(arrayList03))
print(getAbsNumber2(arrayList01))
print(getAbsNumber2(arrayList02))
print(getAbsNumber2(arrayList03))
不论你在什么时候开始,重要的是开始之后就不要停止。
不论你在什么时候结束,重要的是结束之后就不要悔恨。