|
| 1 | +// ! DSA in JavaScript day 5 |
| 2 | + |
| 3 | +// Todo: Topic Array |
| 4 | + |
| 5 | +// * Q3, Remove the duplicate element from Sorted Array |
| 6 | +// * Given an integer array nums sorted in non-decreasing order, remove |
| 7 | +// * the duplicate in-place such that each unique element appears |
| 8 | +// * only once the relative order of elements should ke kept |
| 9 | +// * the same then return the number of unique elements in nums |
| 10 | + |
| 11 | +// * input --> [1,1,2] --> output: 5 |
| 12 | +// * input --> [0,0,1,1,2,2,3,3,4] --> output: 5 |
| 13 | +// [0,0,1,1,2,2,3,3,4] |
| 14 | +// ! :- My answer (Right Answer with Good Time Complexity) |
| 15 | +function CheckUniqueElement(array) { |
| 16 | + let i = 0; |
| 17 | + for (let j = 1; j < array.length; j++) { |
| 18 | + if (array[j] !== array[i]) { |
| 19 | + i++; |
| 20 | + array[i] = array[j]; |
| 21 | + } |
| 22 | + } |
| 23 | + return i + 1; |
| 24 | +} |
| 25 | + |
| 26 | +console.log(CheckUniqueElement([0, 0, 1, 1, 2, 2, 3, 3, 4])); |
| 27 | + |
| 28 | +// ! :- My answer (Right Answer with Good Time Complexity) |
| 29 | +function CheckUniqueElement(array) { |
| 30 | + for (let i = 0; i < array.length - 1; i++) { |
| 31 | + if (array[i] === array[i + 1]) { |
| 32 | + array.splice(i + 1, 1); |
| 33 | + i--; |
| 34 | + } |
| 35 | + } |
| 36 | + return array.length; |
| 37 | +} |
| 38 | + |
| 39 | +console.log(CheckUniqueElement([0, 0, 1, 1, 2, 2, 3, 3, 4])); |
0 commit comments