此代码有效吗? #leetcode #two_sum
这是两个总和 leetcode的问题,我试图解决,它被接受了。我询问此代码在内存和空间复杂性方面是否足够有效。
我的代码:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
l = len(nums)
ans = []
for i in range(l):
compliment = target - nums[i];
# print(a.index(x))
if compliment in nums:
if nums.index(compliment)!=i:
# print(a.index(x))
ans.append(i)
ans.append(nums.index(compliment))
break;
return ans
This is two sum problem from leetcode, I tried to solve, It got accepted. I am asking if this code is efficient enough in terms of memory and space complexity.
My code :
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
l = len(nums)
ans = []
for i in range(l):
compliment = target - nums[i];
# print(a.index(x))
if compliment in nums:
if nums.index(compliment)!=i:
# print(a.index(x))
ans.append(i)
ans.append(nums.index(compliment))
break;
return ans
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码在
nums
中搜索Affiment
,然后以索引函数对其进行跟进。稍后,您在nums.index(Affiment)
中再次使用此索引。本质上,您正在搜索三次的数组。一个更好的方法是搜索数组并存储索引,如果找到了-1
。如果索引不是-1
,即,在数组中存在,则可以将其附加到ANS。这本质上跳过了两行(以及索引
函数),然后一次穿越数组而不是三次。现在,您可以使用此索引
index_if_found
,而不是使用index
函数。编辑:感谢Kelly在搜索算法上纠正我。
此外,您有两个
附加
在同一数组中的方法。一种稍快的方法是使用扩展
方法并将它们添加到同一操作中。所以你没有你
Your code searches for
compliment
innums
, and then follows it up with an index function. Later on, you use this index again innums.index(compliment)
. Essentially, you're searching through the array three times. A better way would be to search through the array and store the index if found, else-1
. If the index is not-1
, i.e., present in the array, you can append it to ans. This essentially skips the two lines (and thatindex
function) and traverses the array once instead of thrice.You can now use this index
index_if_found
instead of using theindex
function.EDIT: Thanks to Kelly for correcting me on the search algorithm.
Additionally, you have two
append
methods to the same array. A slightly faster approach would be to use theextend
method and add them in the same operation. So instead ofYou'd have