zoukankan      html  css  js  c++  java
  • [LeetCode题解]83. 删除排序链表中的重复元素 | 递归 + 迭代

    方法一:递归

    解题思路

    通过递归法,每次判断目前头节点与给定的节点是否相等。如是,继续判断下一个节点,否则保存当前头节点,设置 next 指向下次递归得到的节点,然后返回当前节点。

    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode DeleteDuplicates(ListNode head) {
            // 递归
            if(head == null) {
                return head;
            }
    
            return DeleteDuplicatesRecursion(head, null);
        }
    
        public ListNode DeleteDuplicatesRecursion(ListNode head, ListNode node) {
            if(head == null) {
                return head;
            }
            if(node == null || head.val != node.val) {
                head.next = DeleteDuplicatesRecursion(head.next, head);
                return head;
            } else {
                return DeleteDuplicatesRecursion(head.next, head);
            }
        }
    }
    

    复杂度分析

    • 时间复杂度:(O(n)),其中 (n) 是链表的长度。
    • 空间复杂度:(O(n))。一共调用了 (n) 次递归,需要额外 (O(n)) 的空间。

    方法二:迭代

    解题思路

    通过迭代,判断后一个节点与当前节点是否相同。如是,则“跳过”(删除)此节点。否则,移到下一节点进行判断。

    代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode DeleteDuplicates(ListNode head) {
            ListNode cur = head;
            while (cur != null && cur.next != null) {
                if (cur.next.val == cur.val) {
                    cur.next = cur.next.next;
                } else {
                    cur = cur.next;
                }
            }
            return head;
        }
    }
    

    复杂度分析

    • 时间复杂度:(O(n)),其中 (n) 是链表的长度。因为链表中的每个节点都检查一次以确定它是否重复。
    • 空间复杂度:(O(1))
  • 相关阅读:
    STL map
    HDU1372 Knight Moves BFS
    HDU1072 Nightmare BFS
    discuz论坛发帖添加字段
    gridview自定义button事件 ,无法触发 onrowcommand
    discuz 怎么开启评分!!!
    discuz学习网站收集
    discuz扩展工具集合
    童话世界整理“说说”
    asp.net中Literal与label的区别
  • 原文地址:https://www.cnblogs.com/liang24/p/14015990.html
Copyright © 2011-2022 走看看