|
| 1 | +### [26\. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) |
| 2 | + |
| 3 | +Difficulty: **Easy** |
| 4 | + |
| 5 | + |
| 6 | +Given a sorted array _nums_, remove the duplicates such that each element appear only _once_ and return the new length. |
| 7 | + |
| 8 | +Do not allocate extra space for another array, you must do this by **modifying the input array** with O(1) extra memory. |
| 9 | + |
| 10 | +**Example 1:** |
| 11 | + |
| 12 | +``` |
| 13 | +Given nums = [1,1,2], |
| 14 | +
|
| 15 | +Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. |
| 16 | +
|
| 17 | +It doesn't matter what you leave beyond the returned length.``` |
| 18 | +
|
| 19 | +**Example 2:** |
| 20 | +
|
| 21 | +``` |
| 22 | +Given nums = [0,0,1,1,1,2,2,3,3,4], |
| 23 | + |
| 24 | +Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. |
| 25 | + |
| 26 | +It doesn't matter what values are set beyond the returned length. |
| 27 | +``` |
| 28 | +
|
| 29 | +**Clarification:** |
| 30 | +
|
| 31 | +Confused why the returned value is an integer but your answer is an array? |
| 32 | +
|
| 33 | +Note that the input array is passed in by **reference**, which means modification to the input array will be known to the caller as well. |
| 34 | +
|
| 35 | +Internally you can think of this: |
| 36 | +
|
| 37 | +``` |
| 38 | +// nums is passed in by reference. (i.e., without making a copy) |
| 39 | +int len = removeDuplicates(nums); |
| 40 | + |
| 41 | +// any modification to nums in your function would be known by the caller. |
| 42 | +// using the length returned by your function, it prints the first len elements. |
| 43 | +for (int i = 0; i < len; i++) { |
| 44 | + print(nums[i]); |
| 45 | +}``` |
| 46 | + |
| 47 | + |
| 48 | +#### Solution |
| 49 | + |
| 50 | +Language: **Java** |
| 51 | + |
| 52 | +```java |
| 53 | +class Solution { |
| 54 | + public int removeDuplicates(int[] nums) { |
| 55 | + if (nums.length == 0) { |
| 56 | + return 0; |
| 57 | + } |
| 58 | + int len = 1; |
| 59 | + int emptyIndex = -1; // 可以放下一个元素的位置 |
| 60 | + for (int i = 0; i < nums.length - 1; i++) { |
| 61 | + if (nums[i] == nums[i + 1] && emptyIndex == -1) { |
| 62 | + emptyIndex = i + 1; |
| 63 | + } |
| 64 | + if (nums[i] != nums[i + 1]) { |
| 65 | + len++; |
| 66 | + if (emptyIndex!=-1) { |
| 67 | + nums[emptyIndex++] = nums[i + 1]; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + return len; |
| 72 | + } |
| 73 | +} |
| 74 | +``` |
| 75 | + |
0 commit comments