1. 程式人生 > 其它 >Leetcode No.83 Remove Duplicates from Sorted List移除有序陣列中的重複元素(c++實現)

Leetcode No.83 Remove Duplicates from Sorted List移除有序陣列中的重複元素(c++實現)

1. 題目

1.1 英文題目

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.

1.2 中文題目

將兩個升序連結串列合併為一個新的 升序 連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。

1.3輸入輸出

輸入 輸出
head = [1,1,2] [1,2]
head = [1,1,2,3,3] [1,2,3]

1.4 約束條件

  • 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.

2. 分析

2.1 自己的演算法

該演算法邏輯不太清晰
程式碼如下:

class Solution {
 public:
     ListNode* deleteDuplicates(ListNode* head) {
         if (head == nullptr || head->next == nullptr) {
             return head;
         }
         ListNode* ptr = head;
         ListNode ansHead(0);
         ListNode* ans = &ansHead;
         while (ptr != nullptr) {
             ListNode* nextNode = ptr->next;
             if (nextNode != nullptr && nextNode->val == ptr->val) {
                 ptr->next = nextNode->next;
                 if (ptr->next == nullptr || ptr->next->val != ptr->val) {
                     ans->next = ptr;
                     ans = ans->next;
                 }
             }
             else {
                 ans->next = ptr;
                 ans = ans->next;
             }
             ptr = ptr->next;
         }
         return ansHead.next;
     }
 };

參考:https://leetcode.com/problems/merge-two-sorted-lists/discuss/9714/14-line-clean-C%2B%2B-Solution

2.2 大牛演算法

該演算法不僅程式碼簡潔,而且還避免了記憶體洩漏的問題。
程式碼如下:

class Solution {
 public:
     ListNode* deleteDuplicates(ListNode* head) {
         ListNode* cur = head;
         while (cur != nullptr && cur->next != nullptr) {
             if (cur->val == cur->next->val) {
                 ListNode* tmp = cur->next;
                 cur->next = cur->next->next;
                 delete tmp;//刪除重複節點,從而避免記憶體洩漏問題
             }
             else {
                 cur = cur->next;
             }
         }
         return head;
     }
 };

參考:https://leetcode.com/problems/remove-duplicates-from-sorted-list/discuss/1223275/Good-code-without-memory-leak-C%2B%2B-Ez-to-understnad

作者:雲夢士 出處:http://www.cnblogs.com/yunmeng-shi/ 本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,並保留此段宣告,否則保留追究法律責任的權利。