題目給定一個已排序好的linked list,要求將所有重複的node皆刪除,使得每個元素均只出現一次。
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
解題思路:
因為是排序過的,所以只要判斷後面的節點與當前的是否相同,如果後面的節點跟目前的相同,就跳過他。
using System;
namespace _0083._Remove_Duplicates_from_Sorted_List__Easy_
{
class Program
{
static void Main(string[] args)
{
ListNode l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(2);
l1.next.next.next = new ListNode(2);
l1.next.next.next.next = new ListNode(3);
l1.next.next.next.next.next = new ListNode(4);
var result = DeleteDuplicates(l1);
}
public static ListNode DeleteDuplicates(ListNode head)
{
if (head == null || head.next == null) return head;
ListNode curr = head;
while (curr.next != null)
{
if (curr.val == curr.next.val)
curr.next = curr.next.next;
else
curr = curr.next;
}
return head;
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
}
}
「時間/空間複雜度」 (O(N), O(1))