Skip to content

Commit 08f5ad5

Browse files
author
Kai Yang
committed
82. Remove Duplicates from Sorted List II
1 parent 46990d3 commit 08f5ad5

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using System;
2+
using System.Linq;
3+
using Newtonsoft.Json;
4+
using NUnit.Framework;
5+
6+
[TestFixture]
7+
public class TestClass : TestClassBase
8+
{
9+
[TestCase(10, 10, 1000)]
10+
public void TestMethod(int maxLength, int maxValue, int repeatTimes)
11+
{
12+
Repeat(repeatTimes, () => {
13+
var listValues = GenerateIntegerArray(maxLength, maxValue);
14+
Array.Sort(listValues);
15+
var head = ListNode.GetHead(listValues);
16+
var result = new Solution().DeleteDuplicates(head);
17+
Assert.AreEqual(JsonConvert.SerializeObject(listValues.Where(v => listValues.Count(v2 => v2 == v) == 1)), ListNode.Serialize(result), JsonConvert.SerializeObject(listValues));
18+
});
19+
}
20+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
public class Solution {
2+
private ListNode newHead;
3+
private ListNode last;
4+
private ListNode candidate;
5+
private int count;
6+
7+
public ListNode DeleteDuplicates(ListNode head) {
8+
while (head != null)
9+
{
10+
if (candidate == null || candidate.val != head.val)
11+
{
12+
TryAppend();
13+
candidate = head;
14+
count = 1;
15+
}
16+
else
17+
{
18+
++count;
19+
}
20+
21+
head = head.next;
22+
}
23+
TryAppend();
24+
if (last != null) last.next = null;
25+
return newHead;
26+
}
27+
28+
private void TryAppend()
29+
{
30+
if (count == 1)
31+
{
32+
if (newHead == null)
33+
{
34+
newHead = last = candidate;
35+
}
36+
else
37+
{
38+
last.next = candidate;
39+
last = last.next;
40+
}
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)