python返回两个有序数组的交集

kernelkoder 2020-04-23 12:46:06
python返回两个有序数组的交集
Write a program which takes as hput two sorted arrays, and returns a new array containing
elements that are present in both of the input arrays. The input arrays may have duplicate entries,
but the returned array should be free of duplicates. For example, the input is <2,3,3,5,5,6,7,7,8,12>
and (5,5,6,8 ,8,9,70,10), your output should be (5, 6, 8).
Hinf: Solve the problem if the input array lengths diffur by orders of magnitude. What if they are approximately
equal?
Solution: The brute-force algorithm is a "loop join" , i.e., traversing through all the elements of one
array and comparing them to the elements of the other array. Letm and n be the lengths of the two
input arrays

def intersect-two-sorted-arrays (A, B) :
return [a for i, a in enumerate(A)if (i== 0 or a != A[i - 1]) and a in B]
-----------
上面这个i==0是什么含义?
...全文
189 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kernelkoder 2020-04-24
  • 打赏
  • 举报
回复
感谢各位指点
cool_sql_9 2020-04-24
  • 打赏
  • 举报
回复
引用 2 楼 chuifengde 的回复:
如果A改一下示例为:<2,3,3,5,5,6,7,7,8,12,9,8>那结果是多少?
楼主的问题中A是有序数组吧 如果不是 就先排序
weixin_45903952 2020-04-23
  • 打赏
  • 举报
回复
i==0时,A[i-1]下标越界
chuifengde 2020-04-23
  • 打赏
  • 举报
回复
如果A改一下示例为:<2,3,3,5,5,6,7,7,8,12,9,8>那结果是多少?
cool_sql_9 2020-04-23
  • 打赏
  • 举报
回复
i==0是对A数组中第一个数做的特殊处理,因为对第一个数,没法进行a != A[i - 1]的比较

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧