📅  最后修改于: 2023-12-03 14:54:51.444000             🧑  作者: Mango
教资会网络(UGC NET)是印度教育部主管的印度国家水准考试,旨在选拔大学和学院的各类声誉、副教授和教授职位。考试分为三个考试:纸质I,II和III,其中II和III是计算机科学相关的。本题涉及的是2018年7月II期的UGC NET计算机科学和应用,问题96.本题涉及到数据结构和算法的概念和应用。
已知一个长度为n的未排序数组,其中元素的值范围在1到n^2之间,求该数组中的任意一个重复元素。时间复杂度必须为O(n)
def find_duplicate(arr):
n = len(arr)
num_blocks = int(n ** 0.5)
block_size = int(n ** 0.5)
# 创建块
blocks = [[] for i in range(num_blocks)]
# 将元素放入块
for i in range(n):
block_idx = int(arr[i] / block_size)
blocks[block_idx].append(arr[i])
# 统计每块元素出现的次数
count = [0] * n
for block in blocks:
if block:
for num in block:
count[num-1] += 1
if count[num-1] > 1:
return num
return None
arr = [1, 2, 3, 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, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 6]
print(find_duplicate(arr)) # 3