# Check If N and Its Double Exist
Given an array
arr
of integers, check if there exists two integersN
andM
such thatN
is the double ofM
( i.e.N = 2 * M
).More formally check if there exists two indices
i
andj
such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
解题思路:
对arr的每个num乘以2得出新的list,然后看list里的值是否也在arr里。
遇到两个edge case:
1)arr里有一个0,就会有假true,所以list里的值即使在arr里,这个值也不能是0;
2)arr里有两个0,因为我之前设定的条件排除了0,得到了假的false。所以这里必须算上2个0就也是true的情况。
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
new = []
for num in arr:
new.append(num*2)
for num in arr:
if num in new and (num != 0 or arr.count(0) == 2):
return True
return False
runtime:
步骤有点多余了。参考一下39ms的思路。
39ms 的solution:
如果arr里的0超过1个,就直接True;
不然就把arr里的0全部去掉。然后用之前的那个判别标准。但没必要生成一个新的list,直接for循环时,看num*2是否再arr里。
重写一遍:
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
if arr.count(0) > 1:
return True
S = set(arr) - {0}
for num in S:
if num*2 in S:
return True
return False
runtime:
#941 Valid Mountain Array
Given an array of integers
arr
, returntrue
if and only if it is a valid mountain array.Recall that arr is a mountain array if and only if:
arr.length >= 3
- There exists some
i
with0 < i < arr.length - 1
such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
解题思路:
1)先排除掉长度小于3,最大值在头尾,以及邻近值相等的情况;
2)最大值之前的每个值都应该比右邻值要小,以及最大值之后的每个值都要比右邻值要大。
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
length = len(arr)
max_idx = arr.index(max(arr))
if length < 3 or max_idx == 0 or max_idx == (length - 1):
return False
for i in range(max_idx):
if arr[i] >= arr[i+1]:
return False
for i in range(max_idx, length-1):
if arr[i] <= arr[i+1]:
return False
return True
runtime:
啊哦。看一下190ms的。
看不出和我的思路有什么更快的优势……
看到还有一种思路是用pointer,从左走到右,看看能不能走通。
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
destination = len(arr) - 1
pointer = 0
if destination < 2:
return False
while pointer < destination and arr[pointer] < arr[pointer+1]:
pointer += 1
if pointer == 0 or pointer == destination:
return False
while pointer < destination and arr[pointer] > arr[pointer+1]:
pointer += 1
return pointer == destination
runtime:
只快了一点点……
明天再找找有没有更快的思路。
5月17号再参考了184ms的思路。是把上升下降都默认设置为false。然后看下一个值比上一个值,是否更大或更小,更大说明上升,但前提是之前没有经历过下降;更小说明下降,但前提是之前经历过了上升。一样大就要false。
最后上升下降都是True,才能算True.
重新写了一遍:
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
prev = 0
ascend = False
descend = False
for i in arr[1:]:
if i == arr[prev]:
return False
if i > arr[prev]:
if descend:
return False
ascend = True
if i < arr[prev]:
if not ascend:
return False
descend = True
prev += 1
return ascend and descend
跑出来runtime还是很慢。算了。