-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove Duplicates from Sorted ArrayI&&II.java
More file actions
43 lines (38 loc) · 1.18 KB
/
Remove Duplicates from Sorted ArrayI&&II.java
File metadata and controls
43 lines (38 loc) · 1.18 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
43
/*
the new array should always be unique
so we could start from thinking of A[0] A[1] A[2]...
everytime we compare the element with former element to see if it is equal
not equal, size ++, otherwise skip it and compare next element
so the index of new array won't be changed until we find a different element
const time and const space
if we use hashset, the space complexcity is O(n)
*/
public class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0 || nums == null) return 0;
int index = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != nums[index]){
nums[++index] = nums[i];
}
}
return index + 1;
}
}
//Remove Duplicates from Sorted Array II
/*
follow up 是允许数列中每个数字出现次数为N,其实大同小异
index = n;
*/
public class Solution {
public int removeDuplicates(int[] nums, int n) {
if(nums.length == 0 || nums == null) return 0;
int index = n;
for(int i = n; i < nums.length; i++){
if(nums[i] != nums[i - n]){
nums[index++] = nums[i];
}
}
return index;
}
}