Day 17 - Remove Duplicates from Sorted List

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
废话不多说开始今天的解题Day~


83. Remove Duplicates from Sorted List

Question

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

Example1

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

Example2

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.

解题

题目

首先先简单的翻译一下题目
给一个排序过後的linked list,要把其中重复的节点删除。

Think

作法大致上是这样

  • once用来存有出现一次的值,再抓到每个节点的值的时候就进来判断有没有遇到过,没有就存入。
  • 有出现过的话,就把前一个节点的next指向现在这个节点的next,就完成啦~
  • C版本的话,只差在判断是否重复的方式不是用阵列去存,因为後来发现因为有排序过,只要存一个判断有没有重复就好~

Code

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        once = []
        start = head
        previous = None
        
        while start != None:
            print(start.val)
            if start.val not in once:
                once.append(start.val)
                previous = start
            else:
                previous.next = start.next

            start = start.next
            
        return head

C

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* deleteDuplicates(struct ListNode* head){
    int num = -101;
    struct ListNode* start = head;
    struct ListNode* previous = 0;
    
    while (start != 0){
        // printf("%d\n", start->val);
        // printf("%d\n", start->next);
        
        if (start == head){
            num = start->val;
            previous = start;
        } else {
            if (start->val > num){
                num = start->val;
                previous = start;
            } else if (start->val == num){
                previous->next = start->next;
            }
        }
        
        start = start->next;
    }
    return head;
}

Result

  • Python

  • C

大家明天见/images/emoticon/emoticon29.gif


<<:  【Day 17】递回 Recursion

>>:  [从0到1] C#小乳牛 练成基础程序逻辑 Day 17 - while 无穷回圈

[D16] CNN应用

CNN在影像处理、辨识都是很重要的技术,在上一篇已经稍微了解 CNN 的概念後,现在来看看这个实用的...

D25 - 如何用 Apps Script 自动化地创造与客制 Google Sheet?(二)结合股票价格通知与信件

今天的目标: 帮自己用 Google Sheet 和 GAS 做一个数值到了就用 mail 提醒的程...

IT铁人DAY 4-物件导向基本概念(3)

修饰符(Modifier)   上一篇有讲到封装的特性,也就是把一个类别要运行操作所需用到的资讯都包...

Re-architect - StickyNoteView

上一次我们完成了 ContextMenu 的部分,ContextMenu 也有了属於自己的 View...

Day16-Kubernetes 那些事 - Resource Quotas

前言 昨天的文章讲完 Deployment 以及 ReplicaSet 後相信大家应该对於如何产生更...