1346. 检查整数及其两倍数是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
# 暴力枚举方法
# for i in range(len(arr)):
# for j_value in arr[i+1:]:
# if arr[i]==2*j_value or 2*arr[i]==j_value:
# return True
# return False
# 二分法
arr.sort()
while len(arr)>1:
if arr[len(arr)-1]>=0: # 正数
last = arr.pop()
left = 0
right = len(arr)-1
while left<=right:
mid = (left+right)>>1
if 2*arr[mid]==last:
return True
elif 2*arr[mid]>last:
right = mid-1
else:
left = mid+1
if arr[len(arr)-1]<0: # 负数
first = arr.pop(0)
left = 0
right = len(arr)-1
while left<=right:
mid = (left+right)>>1
if 2*arr[mid]==first:
return True
elif 2*arr[mid]>first:
right = mid-1
else:
left = mid+1
return False