Re: [閒聊] 每日leetcode

作者: dont   2024-11-11 21:03:34
2601. Prime Subtraction Operation
## 思路
假如新遞增陣列的前一個值是prev,
下一個值 num-prime 要大於 prev
=> 先建質數表, 掃陣列用Binary Search找最大可能的prime 並更新prev
## Code
```python
class Solution:
def primeSubOperation(self, nums: List[int]) -> bool:
is_prime = [True] * 1001
is_prime[0] = is_prime[1] = False
for i in range(2, int(sqrt(1001)) + 1):
if not is_prime[i]:
continue
for j in range(2*i, 1001, i):
is_prime[j] = False
primes = [i for i in range(2, 1001) if is_prime[i]]
prev = 0
for num in nums:
if num <= prev:
return False
idx = bisect_left(primes, num - prev) - 1
prev = num - primes[idx] if idx != -1 else num
return True
```
作者: DJYOMIYAHINA (通通打死)   2024-11-11 21:04:00
大師
作者: sustainer123 (caster)   2024-11-11 21:07:00
大師
作者: CP3isgood (3345678)   2024-11-11 21:09:00
大師
作者: JerryChungYC (JerryChung)   2024-11-11 21:17:00
剩我什麼都不會了
作者: sixB (6B)   2024-11-11 22:01:00
酷 沒想到可以二分搜

Links booklink

Contact Us: admin [ a t ] ucptt.com