forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_26.java
58 lines (53 loc) · 1.35 KB
/
_26.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.fishercoder.solutions;
/**
* 26. Remove Duplicates from Sorted Array
*
* Given a sorted array, remove the duplicates
* in place such that each element appear only once and return the new length.
* Do not allocate extra space for another array, you must do this in place with constant memory.
*
* For example,
* Given input array A = [1,1,2],
* Your function should return length = 2, and A is now [1,2].
* */
public class _26 {
public static class Solution1 {
public int removeDuplicates(int[] nums) {
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[i] != nums[j]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
}
public static class Solution2 {
/**
* Same idea as the editorial solution, mine just got more verbose.
*/
public static int removeDuplicates(int[] nums) {
int i = 0;
for (int j = i + 1; i < nums.length && j < nums.length; ) {
while (j < nums.length && nums[i] == nums[j]) {
j++;
}
if (j == nums.length) {
j--;
}
int temp = nums[j];
nums[j] = nums[i + 1];
nums[i + 1] = temp;
if (nums[i] != nums[i + 1]) {
i++;
}
if (j == nums.length) {
break;
}
j++;
}
return i + 1;
}
}
}