-
Notifications
You must be signed in to change notification settings - Fork 161
/
remove-duplicates-from-sorted-array-ii.md
41 lines (26 loc) · 2.08 KB
/
remove-duplicates-from-sorted-array-ii.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<p>Given a sorted array <em>nums</em>, remove the duplicates <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a> such that duplicates appeared at most <em>twice</em> and return the new length.</p>
<p>Do not allocate extra space for another array, you must do this by <strong>modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a></strong> with O(1) extra memory.</p>
<p><strong>Example 1:</strong></p>
<pre>
Given <em>nums</em> = <strong>[1,1,1,2,2,3]</strong>,
Your function should return length = <strong><code>5</code></strong>, with the first five elements of <em><code>nums</code></em> being <strong><code>1, 1, 2, 2</code></strong> and <strong>3</strong> respectively.
It doesn't matter what you leave beyond the returned length.</pre>
<p><strong>Example 2:</strong></p>
<pre>
Given <em>nums</em> = <strong>[0,0,1,1,1,1,2,3,3]</strong>,
Your function should return length = <strong><code>7</code></strong>, with the first seven elements of <em><code>nums</code></em> being modified to <strong><code>0</code></strong>, <strong>0</strong>, <strong>1</strong>, <strong>1</strong>, <strong>2</strong>, <strong>3</strong> and <strong>3</strong> respectively.
It doesn't matter what values are set beyond the returned length.
</pre>
<p><strong>Clarification:</strong></p>
<p>Confused why the returned value is an integer but your answer is an array?</p>
<p>Note that the input array is passed in by <strong>reference</strong>, which means modification to the input array will be known to the caller as well.</p>
<p>Internally you can think of this:</p>
<pre>
// <strong>nums</strong> is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to <strong>nums</strong> in your function would be known by the caller.
// using the length returned by your function, it prints the first <strong>len</strong> elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
</pre>