C#LeetCode刷题之#83-删除排序链表中的重复元素(Remove Duplicates from Sorted List)

C#LeetCode刷题之#83-删除排序链表中的重复元素(Remove Duplicates from Sorted List)

问题

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

输入: 1->1->2

输出: 1->2

输入: 1->1->2->3->3

输出: 1->2->3

Given a sorted linked list, delete all duplicates such that each element appear only once.

Input: 1->1->2

Output: 1->2

Input: 1->1->2->3->3

Output: 1->2->3

示例

public class Program {

    public static void Main(string[] args) {
        var head = new ListNode(1) {
            next = new ListNode(1) {
                next = new ListNode(2) {
                    next = new ListNode(3) {
                        next = new ListNode(3)
                    }
                }
            }
        };

        var res = DeleteDuplicates(head);
        ShowArray(res);

        Console.ReadKey();
    }

    private static void ShowArray(ListNode list) {
        var node = list;
        while(node != null) {
            Console.Write($"{node.val} ");
            node = node.next;
        }
        Console.WriteLine();
    }

    private static ListNode DeleteDuplicates(ListNode head) {
        if(head == null) return null;
        var cur = head;
        var next = cur.next;
        while(cur != null && next != null) {
            while(next != null && cur.val == next.val) {
                next = next.next;
            }
            cur.next = next;
            cur = next;
            next = cur?.next;
        }
        return head;
    }

    public class ListNode {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

1 2 3

分析:

显而易见,以上算法的时间复杂度为: O(n^{2})

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3820

发表评论

登录后才能评论