- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在 CodeFights.com 上尝试 sumOFTwo 挑战,但不幸的是我无法完成它以查看解决方案。我所有的测试都成功了,直到第 15 次隐藏测试,它说它超过了时间限制。
挑战是 - 你有两个整数数组 a 和 b,以及一个整数目标值 v。确定是否存在一对数字,其中一个数字取自 a,另一个取自 b,并且可以相加一起得到 v 的和。如果存在这样的对,则返回 true,否则返回 false。
我的代码是 -
def sumOfTwo(a,b,v):
a.sort()
b.sort()
if(0 in a and v in b):
return True
elif(v in a and 0 in b):
return True
else:
for i in a:
for j in b:
if(i + j == v):
return True
return False
我知道它可以缩减到大约 6 行代码,但我一直在添加可以帮助代码更快完成的代码行。我还缺少其他优化吗?
最佳答案
您可以将其中一个列表转为 set
,遍历另一个列表并查看 v - value_from_list
是否存在于 set
中:
def sumOfTwo(a,b,v):
b = set(b)
return any(v - x in b for x in a)
print(sumOfTwo([3, 6, 7], [2, 1], 9))
print(sumOfTwo([3, 6, 7], [2, 1], 10))
print(sumOfTwo([3, 6, 7], [2, 1], 4))
print(sumOfTwo([3, 6, 7], [2, 1], 3))
输出:
True
False
True
False
上述的时间复杂度为O(n)。
关于python - sumOfTwo Time Limit Exceeded CodeFights 面试实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42336827/
我很难用 JavaScript 解决这个问题 给你一个字符串 s,它由英文字母、标点符号、空白字符和方括号组成。保证 s 中的括号形成一个规则的括号序列。 你的任务是反转每对匹配括号中的字符串,从最里
根据问题陈述: Write a solution with O(n) time complexity and O(1) additional space complexity. Given an ar
到目前为止,我已经做到了。我坚持递归。我不知道如何前进,加入和倒退等等。 def callrecursion(s): a=s.index('(') z=len(s) - string[
给定一个整数序列作为一个数组,确定是否可以通过从数组中删除不超过一个元素来获得一个严格递增的序列。 例子 对于序列[1, 3, 2, 1],输出应该是: almostIncreasingSequenc
我在介绍中遇到了 Codefights Arcade 问题 13 中的一个问题。以下是到目前为止的问题陈述和我的代码。我对如何解决这个问题的想法是递归地向下/在嵌套序列内工作,当我到达一个序列(没有嵌
我正在 codefights.com 练习编码。这是查看他们要求的链接:link .我很难理解这些 return 语句在下面的代码中到底做了什么。 我的代码: def avoidObstacles(i
我在使用 python3 的 CodeFights 上遇到了“areSimilar”问题。 提示指出“如果可以通过交换一个数组中的最多一对元素从另一个数组中获得一个数组,则两个数组被称为相似。 给定两
根据 Codefighters: 注意:编写一个具有 O(n) 时间复杂度和 O(1) 额外空间复杂度的解决方案,因为这是您在真实面试中被要求做的事情。 给定一个仅包含从 1 到 a.length 范
我正在尝试从 CodeFights 解决以下问题。问题结束后,我用 Java 留下了答案。该代码适用于除最后一个问题之外的所有问题。报时限异常。我该怎么做才能让它运行在 3000 毫秒以下(CodeF
我日常任务的目标是计算给定数组 (int [] a) 中表示了多少组整数(从 1 到 10000、10001 到 20000 等,直到 1000000)(例如,a[ 0] =2,所以属于第1组)。 我
我目前正在研究 Code Fights Arcade 的 arrayChange 关卡。这是目标: 给你一个整数数组。在每一步中,您都可以 恰好将其元素之一增加一。找到最小数量的 从输入中获得严格递增
我无法通过最后的隐藏测试。你能告诉我我错过了什么吗?提前致谢。 语句如下:给定一个整数序列作为数组,确定是否可以通过从数组中删除不超过一个元素来获得严格递增的序列。 boolean almostInc
给定一个由单位正方形组成的矩形 (m,n) 的尺寸,输出与矩形对角线相交的单位正方形的数量 - 包括边界和顶点。 我的算法通过循环遍历所有单位正方形来解决这个问题(假设可以绘制我们的对角线从 (0,0
我在 CodeFights.com 上看到过 C++ 函数的这种语法形式: int i,j,w,myFunction(auto s, auto v) { // here, i, j,and w a
来自 Codefighters: Note: Write a solution with O(n) time complexity and O(1) additional space complexi
我正在做 codefight 的挑战:扫雷。 描述: 我的代码如下: def minesweeper(matrix): for x in range(len(matrix)):
我正在 CodeFights.com 上尝试 sumOFTwo 挑战,但不幸的是我无法完成它以查看解决方案。我所有的测试都成功了,直到第 15 次隐藏测试,它说它超过了时间限制。 挑战是 - 你有两个
所以我必须找到包含 n 位数字的最大数字。例如,如果 n=2,那么 largestNumber = 99。这就是我的答案。 function largestNumber(n) { var nu
我是一名优秀的程序员,十分优秀!