LeetCode集锦(十九) - 第83题 Remove Duplicates from sorted list

问题

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

 Example 1: 


Input: 1->1->2
Output: 1->2


 Example 2: 


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

复制代码

翻译:

给定一个已排序的链表,删除全部重复项,使每一个元素只出现一次。 示例1: 输入:1 - > 1 - > 2 输出:1 - > 2 示例2: 输入:1 - > 1 - > 2 - > 3 - > 3 输出:1 - > 2 - > 3bash


解题思路

本题思路很简单,因为链表是有序的,说明若是有重复的,确定是下一个,按照顺序进行遍历,若是遇到当前节点和后一个节点相同,那么覆盖当前节点。遍历一次就搞定了app

解题方法

  1. 按照咱们的思路来编辑,代码以下ui

    public ListNode deleteDuplicates(ListNode head) {
    
        if (head == null) {
            return head;
        }
    
        ListNode temp = head;
        while (head.next != null) {
            if (head.val == head.next.val) {
                head.next = head.next.next;
                continue;
            }
            head = head.next;
        }
        return temp;
    
    }
    
    public class ListNode {
        int val;
        ListNode next;
    
        ListNode(int x) {
            val = x;
        }
    }
    复制代码

    时间复杂度: 该方案用了循环m因此f(n)=(n)=n;因此O(f(n))=O(n),即T(n)=O(n)spa

    空间复杂度: 该方案使用了没有使用额外空间,因此空间复杂度是O(n)=O(1);翻译

总结

本题的大体解法如上所诉,本题大体只有一种解题方式,直接遍历读取覆盖便可,我是经过当前节点和下一个节点进行比较,也能够和前一个节点进行比较 。code

相关文章
相关标签/搜索