LeetCode82-删除排序链表中的重复元素 II
今天是妇女节
我当然也要与之同庆了
所以今天写两篇文章
一大早就和我两个姐和老杨分别发红包祝福
每次到这时候以及过生日
才感觉家里女同袍多也是一件忧伤的事
哈哈哈哈哈哈哈哈
但没办法
谁叫她们是我姐和我老妈呢
我就是爱她们!!!
82-删除排序链表中的重复元素 II
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
思路:
本题是上一题83-删除排序链表中的重复元素的进化版,对上一题不太熟悉的读者可以先看看我写的文章。
https://blog.****.net/weixin_36431280/article/details/88326800
本题的步骤主要如下:
- 首先将head指针对应的每个结点的值存储到一列表中
- 然后对该列表去重复数字,判断方法就是:if head_list.count(index) > 1: 则舍弃该元素
- 将去重之后的列表重新赋值给一链表
代码如下:
class Solution(object):
# 此种解法步骤:1. 首先将head指针对应的每个结点的值存储到一列表中
# 2. 然后对该列表去重复数字,判断方法就是:if head_list.count(index) > 1: 则舍弃该元素
# 3. 将去重之后的列表重新赋值给一链表
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 首先将head指针对应的每个结点的值存储到一列表中
head_copy = head
head_list = []
while head_copy is not None:
head_list.append(head_copy.val)
head_copy = head_copy.next
# 定义一same_list列表用来保存去重之后的数组元素
same_list = []
# 然后对该列表去重复数字
for index in head_list:
if head_list.count(index) == 1:
same_list.append(index)
# 将去重之后的列表重新赋值给一链表
new_head = ListNode(0)
new_head_copy = new_head
for index in same_list:
new_head_copy.next = ListNode(index)
new_head_copy = new_head_copy.next
return new_head.next
if __name__ == "__main__":
head_list = [2, 1]
head = ListNode(0)
head_copy = head
for index in head_list:
head_copy.next = ListNode(index)
head_copy = head_copy.next
new_head = Solution().deleteDuplicates(head.next)
print(new_head)
执行效率奇低,官方都不好意思给出具体的数值了,惭愧惭愧!!!