难度指数:⭐⭐⭐⭐
通用一般算法:
def solve(desk):
n = len(desk)
count = 0 # 用于记录可以坐的人数
i = 0
while i < n:
# 当前位置为空位且满足左右都是空位的条件
if desk[i] == 0:
left_empty = i == 0 or desk[i - 1] == 0
right_empty = i == n - 1 or desk[i + 1] == 0
if left_empty and right_empty:
count += 1
desk[i] = 1
i += 1 # 如果当前位置可以坐人,那么下一个位置一定不可以,因此直接跳过
i += 1
return count
创新算法
idea
代码实现
def solve0():
nums1 = [1, 0] + nums + [0, 1]
count0 = []
temp = 0
for i in nums1:
if i == 1:
if temp > 2:
count0.append(temp)
temp = 0
else:
temp += 1
counter0 = Counter(count0)
res = 0
for k, v in counter0.items():
res += (k-1)//2 * v
return res
对比验证
耗时:
from time import time
import random
from collections import Counter
def solve(desk):
n = len(desk)
count = 0 # 用于记录可以坐的人数
i = 0
while i < n:
# 当前位置为空位且满足左右都是空位的条件
if desk[i] == 0:
left_empty = i == 0 or desk[i - 1] == 0
right_empty = i == n - 1 or desk[i + 1] == 0
if left_empty and right_empty:
count += 1
desk[i] = 1
i += 1 # 如果当前位置可以坐人,那么下一个位置一定不可以,因此直接跳过
i += 1
return count
def solve0():
nums1 = [1, 0] + nums + [0, 1]
count0 = []
temp = 0
for i in nums1:
if i == 1:
if temp > 2:
count0.append(temp)
temp = 0
else:
temp += 1
counter0 = Counter(count0)
res = 0
for k, v in counter0.items():
res += (k-1)//2 * v
return res
T = 10
while T:
nums = [random.randint(0, 1) for _ in range(random.randint(1, 2e4))]
t1 = time()
res0 = solve0()
t3 = time()
res = solve(nums)
t2 = time()
if res != res0:
print(res, res0)
print(t2 - t3, t3 - t1)
T -= 1