-
Notifications
You must be signed in to change notification settings - Fork 0
/
26-removeElement.js
47 lines (39 loc) · 977 Bytes
/
26-removeElement.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
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function (nums, val) {
if (nums.length === 0) {
return [];
}
let banishToTheEndOfTheArray = (index) => {
let temp = nums[index];
let bubbleIndex = index + 1;
while (bubbleIndex < nums.length) {
nums[bubbleIndex - 1] = nums[bubbleIndex];
bubbleIndex++;
}
nums[nums.length - 1] = temp;
};
let noBanished = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] === val) {
if (noBanished > nums.length) {
break;
}
banishToTheEndOfTheArray(i);
noBanished++;
i--;
}
}
for (let i = 0; i < nums.length; i++) {
if (nums[i] === val) {
return i;
}
}
return nums.length;
};
const arr = [2, 2, 3];
console.log(removeElement(arr, 3));
console.log(arr);