3
3
/**
4
4
* 26. Remove Duplicates from Sorted Array
5
5
*
6
- * Given a sorted array, remove the duplicates
7
- * in place such that each element appear only once and return the new length.
8
- * Do not allocate extra space for another array, you must do this in place with constant memory.
6
+ * Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
7
+ * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
9
8
*
10
- * For example,
11
- * Given input array A = [1,1,2],
12
- * Your function should return length = 2, and A is now [1,2].
9
+ * Example 1:
10
+ * Given nums = [1,1,2],
11
+ * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
12
+ * It doesn't matter what you leave beyond the returned length.
13
+ *
14
+ * Example 2:
15
+ * Given nums = [0,0,1,1,1,2,2,3,3,4],
16
+ * Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
17
+ * It doesn't matter what values are set beyond the returned length.
18
+ *
19
+ * Clarification:
20
+ * Confused why the returned value is an integer but your answer is an array?
21
+ * 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.
22
+ * Internally you can think of this:
23
+ * // nums is passed in by reference. (i.e., without making a copy)
24
+ * int len = removeDuplicates(nums);
25
+ *
26
+ * // any modification to nums in your function would be known by the caller.
27
+ * // using the length returned by your function, it prints the first len elements.
28
+ * for (int i = 0; i < len; i++) {
29
+ * print(nums[i]);
30
+ * }
13
31
* */
14
32
15
33
public class _26 {
16
34
17
35
public static class Solution1 {
36
+ /**Key: It doesn't matter what you leave beyond the returned length.*/
18
37
public int removeDuplicates (int [] nums ) {
19
38
int i = 0 ;
20
39
for (int j = 1 ; j < nums .length ; j ++) {
@@ -26,33 +45,4 @@ public int removeDuplicates(int[] nums) {
26
45
return i + 1 ;
27
46
}
28
47
}
29
-
30
- public static class Solution2 {
31
- /**
32
- * Same idea as the editorial solution, mine just got more verbose.
33
- */
34
- public static int removeDuplicates (int [] nums ) {
35
- int i = 0 ;
36
- for (int j = i + 1 ; i < nums .length && j < nums .length ; ) {
37
- while (j < nums .length && nums [i ] == nums [j ]) {
38
- j ++;
39
- }
40
- if (j == nums .length ) {
41
- j --;
42
- }
43
- int temp = nums [j ];
44
- nums [j ] = nums [i + 1 ];
45
- nums [i + 1 ] = temp ;
46
- if (nums [i ] != nums [i + 1 ]) {
47
- i ++;
48
- }
49
- if (j == nums .length ) {
50
- break ;
51
- }
52
- j ++;
53
- }
54
- return i + 1 ;
55
- }
56
- }
57
-
58
48
}
0 commit comments