-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremoveDuplicatesFromSortedArray.js
51 lines (42 loc) · 1.06 KB
/
removeDuplicatesFromSortedArray.js
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
'use strict';
const removeDuplicates = function(nums) {
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[i] != nums[j]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[i] === nums[j]) {
nums.slice(i, j + 1);
}
}
return nums;
// another way without making an extra space (O(1))
const removeDuplicates = function(nums) {
// make a function that returns a unique value
function unique(num, index) {
return nums.indexOf(num) === index;
}
// filter the array with unique values using a separate function
nums = nums.filter(unique);
// return the length of the array
return nums.length;
}
// O(N) memory
// const removeDuplicates = function(nums) {
// // make a Set to store unique values
// let set = new Set();
// // add each element of the array to the Set
// for (let num of nums) {
// set.add(num);
// }
// // return the size of the Set
// return set.size;
// }
let nums = [0,0,1,1,1,2,2,3,3,4];
console.log(removeDuplicates(nums));