zoukankan      html  css  js  c++  java
  • [LeetCode] 83. Remove Duplicates from Sorted List

    Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

    Example 1:

    Input: head = [1,1,2]
    Output: [1,2]
    

    Example 2:

    Input: head = [1,1,2,3,3]
    Output: [1,2,3]

    Constraints:

    • The number of nodes in the list is in the range [0, 300].
    • -100 <= Node.val <= 100
    • The list is guaranteed to be sorted in ascending order.

    删除排序链表中的重复元素。

    思路很简单,每次去看一下当前节点和下一个节点的val是否相同,如是,则跳过下一个节点。

    时间O(n)

    空间O(1)

    注意1 - 1 - 1这样的case怎么处理。当满足if的条件的时候,一定要写else。

    JavaScript实现

     1 /**
     2  * Definition for singly-linked list.
     3  * function ListNode(val) {
     4  *     this.val = val;
     5  *     this.next = null;
     6  * }
     7  */
     8 /**
     9  * @param {ListNode} head
    10  * @return {ListNode}
    11  */
    12 var deleteDuplicates = function(head) {
    13     // corner case
    14     if (head === null || head.next === null) {
    15         return head;
    16     }
    17 
    18     // normal case
    19     let cur = head;
    20     while (cur !== null && cur.next !== null) {
    21         if (cur.val === cur.next.val) {
    22             cur.next = cur.next.next;
    23         } else {
    24             cur = cur.next;
    25         }
    26     }
    27     return head;
    28 };

    Java实现

     1 class Solution {
     2     public ListNode deleteDuplicates(ListNode head) {
     3         // corner case
     4         if (head == null || head.next == null) {
     5             return head;
     6         }
     7 
     8         // normal case
     9         ListNode cur = head;
    10         while (cur.next != null) {
    11             if (cur.next.val == cur.val) {
    12                 cur.next = cur.next.next;
    13             } else {
    14                 cur = cur.next;
    15             }
    16         }
    17         return head;
    18     }
    19 }

    相关题目

    83. Remove Duplicates from Sorted List

    82. Remove Duplicates from Sorted List II

    1836. Remove Duplicates From an Unsorted Linked List

    LeetCode 题目总结

  • 相关阅读:
    [实战]MVC5+EF6+MySql企业网盘实战(11)——新建文件夹2
    [实战]MVC5+EF6+MySql企业网盘实战(10)——新建文件夹
    FMXUI
    x-superobject
    mORMot
    NativeXml
    superobject
    jsondataobjects
    QDAC
    DIOCP
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11817311.html
Copyright © 2011-2022 走看看