203. Remove Linked List Elements

来源:互联网 发布:梦里花落知多少句子 编辑:程序博客网 时间:2024/04/30 18:04

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

题目不难,但是经历了一个代码渐渐优化的过程
删除一个链表元素,重要的是记录删除位置的前驱和后继,因此设置两个指针专门保存待删除元素的前驱和后继,加上待删除元素一共三个指针,程序如下:

class Solution(object):    def removeElements(self, head, val):        """        :type head: ListNode        :type val: int        :rtype: ListNode        """        if not head:            return None        p = head        q = p.next        pre = ListNode(-1)        pre.next = p        h = pre        while p != None:            if p.val == val:                pre.next = q            else:                pre = pre.next            p = p.next            if p != None:                q = p.next             return h.next

然后AC了,but 看下图时间开销比较大啊,
这里写图片描述
才击败了25.92%的人 T_T,要优化优化才行!
发现其实只要两个指针就可以了,一个保存待删除元素的前驱,一个保存待删除元素,它的后继用next就能得到,我之前傻了啊。
改后程序如下,比原来少了一个pre指针:

class Solution(object):    def removeElements(self, head, val):        """        :type head: ListNode        :type val: int        :rtype: ListNode        """        if not head:            return None        h = ListNode(-1)        h.next = head        p = h        q = p.next        while q != None:            if q.val == val:                p.next = q.next            else:                p = p.next            q = p.next             return h.next

这里写图片描述
时间上快了一点,击败了62%的人,然后继续优化,发现不用加上这个判断:

if not head:    return None

因为以前做题习惯了,总喜欢加上一个判断,避免输入为空的情况,但是这里不需要加,因为while循环位置有判断了。所以果断删除改后代码如下:

class Solution(object):    def removeElements(self, head, val):        """        :type head: ListNode        :type val: int        :rtype: ListNode        """#         if not head: # 没有这句了#             return None        h = ListNode(-1)        h.next = head        p = h        q = p.next        while q != None:            if q.val == val:                p.next = q.next            else:                p = p.next            q = p.next             return h.next

这里写图片描述
击败了90%的人,此时无声胜有声啊,话说那些dalao们是怎么写的程序。

总结:写完程序以后尝试优化优化,不要因为题简单AC就行了,有时候强迫自己一下,或许会有提高呢

0 0
原创粉丝点击