上午做了个笔试,要求解一道in-place删除数组多余内容的算法题,有O(1)的额外空间要求。
完整的描述忘记了。大致的需求如下:
假设有一个有序数组nums = [1, 1, 1, 2, 3, 5, 5, 5],如果数组中的数字出现超过2次,则删除多余的数字。返回删除后的数组长度。
如 nums = [1, 1, 1, 2, 3, 5, 5, 5] 的结果应为nums = [1, 1, 2, 3, 5, 5], 并返回长度6.
虽然没涉及到复杂的结构或逻辑,不过要bare hand写一个bug free的算法还是难到我了。
刚刚凭记忆把卷子上写的代码在电脑上敲了一遍,果然没有通过....
下面是调试通过的代码,不保证是best practice或最简洁,但感觉应该满足题目的要求。时间复杂度不可避免的O(n)了。
def func(a):
index = -1 # 有效下标记录
count = 0
temp = a[0]
for i in range(len(a)):
if temp == a[i]:
count += 1
else:
temp = a[i]
count = 1
if count <= 2:
index += 1
a[index] = a[i]
a = a[:index+1]
return index + 1
if __name__ == '__main__':
a = [1,1,1,2,3,4,4,4,5,9,9]
length = func(a)
a = a[:length] # 尴尬的引用传参,函数外需要额外截断
print(a)
print(length)