-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathArrayDeduplicationI.java
More file actions
42 lines (34 loc) · 1.01 KB
/
ArrayDeduplicationI.java
File metadata and controls
42 lines (34 loc) · 1.01 KB
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
/*
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}
*/
public class Solution {
public static int[] dedup(int[] input) {
if (input.length <= 1 || input == null) {
return input;
}
int slow = 1; // elements to the left of slow are processed and need to be kept (excluding slow)
int fast = 1; // current index
while (fast < input.length) {
if (input[fast] != input[slow - 1]) { // keep it (copy)
input[slow++] = input[fast++];
} else { // ignore it
fast++;
}
}
return reSize(input, slow);
}
private static int[] reSize(int[] input, int slow) {
int[] output = new int[slow];
for (int i = 0; i < slow; i++) {
output[i] = input[i];
}
return output;
}
}