python - 将链表中的元素与列表的其余部分进行比较python
问题描述
所以我在处理当前的问题时遇到了麻烦。该问题提示我们获取一个链表并将每个元素与列表的其余部分进行比较,并返回重复项的总数。例如列表是 [1,2,3,1,4,2,] 这应该返回 2 个重复项 1 和 2。我尝试使用列表的长度循环遍历列表,但仍然得到错误的输出。我在下面提供了我的尝试,提前感谢您的帮助。
def solution1 (llist):
counter = 0
length=0
curr = llist.head
while curr:
length+=1
curr=curr.next
while curr:
for _ in range(length):
if curr.item == curr.next.item:
counter+=1
curr = curr.next
return counter
预期产出——
llist= 1-->2-->3-->1-->4-->2
output:2
解决方案
你快到了。下面是使用嵌套循环的蛮力方法。维持两个柜台first
和second
。每当它们的值匹配时,就意味着它是重复的。增加计数器并继续。
时间复杂度:O(n^2)
def solution1(llist):
counter = 0
first = llist.head
while first:
second = first.next
while second:
if first.item == second.item: # duplicate
counter += 1
break
second = second.next
first = first.next
return counter
一种更优化的方法是在迭代时保持元素计数。返回 count > 1 的键。
时间复杂度:O(n)
import collections
def solution1(llist):
curr = llist.head
counts = collections.defaultdict(int)
while curr:
counts[curr.item] += 1
curr = curr.next
print(counts)
return sum(1 for i in counts if counts[i] > 1)
推荐阅读
- c++ - 将成对向量插入 unordered_map 时 C++ 缺少元素
- flutter - Flutter GridView.builder 不可滚动
- c++ - 转换返回值时的 RVO
- c++ - 为什么线程清理程序抱怨这个 std::ranges::views::filter 代码?
- javascript - Promise 构造函数是否需要 resolve 函数?
- python - AttributeError:“NoneType”对象没有属性“get”(MongoDB 和 Django)
- amazon-web-services - 是否有在 AWS Fargate 上安装持久存储的 docker-compose.yml 示例?
- android - 如何获得平滑的渐变
- javascript - 如何更新 JSP 中输入更改的值?
- api - 为什么我的 WHMCS 在 error_log 中记录“hashReq”