python - 将此 O(N) 线性搜索改进为 O(log N) 时间复杂度
问题描述
我正在尝试解决这个Geeks for Geeks 问题:
查找出现一次的元素
给定一个由 N 个正整数组成的排序数组 A[],其中所有数字恰好出现两次,除了一个仅出现一次的数字。找出只出现一次的数字。
你的任务:
你不需要读取输入或打印任何东西。您的任务是完成函数 search(),它接受两个参数(数组 A 和整数 N)并返回仅出现一次的数字。预期时间复杂度: O(Log(N))。
预期辅助空间: O(1)。约束
0 < N <= 10^6
0 <= A[i] <= 10^9
我的做法:
For Given
Array:A
&Size:N
Initialize i With 0i=0
# i is index reference in array traversal
loop through0 to N-1
# While i<N :
Selecti^th
element fromArray :A
# select=A[i]
Creates A Sub-array(next) does not containselect
# next=A[i +1:]
现在比较next
(子数组)与select
如果它包含select
推送的副本/副本select
到新子数组(previous
)#先前保留访问元素的记录
更新i to +1
并重复此过程
下一个tym新值被i
选为检查子数组select=A[i+1]
中是否存在&& If子数组next
previous
也不包含select
#Hopefully它是第一个遍历的,它是唯一
的, 返回i^th
不在两个数组previous
和next
子数组中的元素
代码:
# Function to recognize singular element i
def check(list,n):
i=0
select=0
next=0
previous=[]
while(i<n):
select=list[i]
next=list[i+1:]
if select in next:
previous.append(select)
elif select in previous:
pass
else:
return select
i+=1
# Driver Code
def main():
list=[]
n =int(input('Enter Size of array:'))
for a in range(0,n):
x=int(input('Array[{}]='.format(a)))
list.append(x)
i=check(list,n)
print('The No.is :',i)
main()
上面的脚本有效,但不是 O(log N)。我尝试删除额外的变量并将额外的子数组转换为变量以减少时间。
解决方案
推荐阅读
- angular - Angular 5 - 在浏览器上维护组件范围硬刷新
- python - 如何使用 Python 获取电子邮件的收件人?
- python - 如何在 Django 中从 Raw Html 获取值
- pdf - 在freemarker中拼接字符串的中间?
- python - 如何检索元素以在两个给定的 txt 文件之间进行匹配?
- java - 创建自定义视图并重用相同的视图
- python - 如何通过 NAPALM 执行“显示运行”命令
- python - 在 Python 中使用 Unix 域套接字 - 如何可能遍历来自套接字的行并在这些行上执行操作?
- atmel - 为 SAMD21 DAC 使用外部 Vref
- android - 如何启动一个包装的活动对象?