-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array Deduplication I.java
49 lines (42 loc) · 1.04 KB
/
Array Deduplication I.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
/*
Given a sorted integer array, remove duplicate elements.
For each group of elements with the same value keep only one of them.
Do this in-place, using the left side of the original array and maintain the relative order of the elements of the array.
Return the array after deduplication.
Assumptions
The array is not null
Examples
{1, 2, 2, 3, 3, 3} → {1, 2, 3}
time = O(n)
space = O(1)
*/
// while version
public class Solution {
public int[] dedup(int[] array) {
// Write your solution here.
if (array == null || array.length == 0) {
return array;
}
int slow = 0;
int fast = 1;
while (fast < array.length) {
if (array[fast] != array[slow]) {
array[++slow] = array[fast++];
} else {
fast++;
}
}
return slow + 1;
}
}
// for version
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
nums[++i] = nums[j];
}
}
return i + 1;
}