-
Notifications
You must be signed in to change notification settings - Fork 160
/
remove-duplicates-from-sorted-array.md
40 lines (25 loc) · 2.08 KB
/
remove-duplicates-from-sorted-array.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
<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 each element appear only <em>once</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,2]</strong>,
Your function should return length = <strong><code>2</code></strong>, with the first two elements of <em><code>nums</code></em> being <strong><code>1</code></strong> and <strong><code>2</code></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,2,2,3,3,4]</strong>,
Your function should return length = <strong><code>5</code></strong>, with the first five elements of <em><code>nums</code></em> being modified to <strong><code>0</code></strong>, <strong><code>1</code></strong>, <strong><code>2</code></strong>, <strong><code>3</code></strong>, and <strong><code>4</code></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>