Skip to content

Commit b655317

Browse files
committed
Remove Element from Array solution
1 parent a6d223c commit b655317

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

26-removeElement.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} val
4+
* @return {number}
5+
*/
6+
var removeElement = function (nums, val) {
7+
if (nums.length === 0) {
8+
return [];
9+
}
10+
11+
let banishToTheEndOfTheArray = (index) => {
12+
let temp = nums[index];
13+
let bubbleIndex = index + 1;
14+
15+
while (bubbleIndex < nums.length) {
16+
nums[bubbleIndex - 1] = nums[bubbleIndex];
17+
bubbleIndex++;
18+
}
19+
20+
nums[nums.length - 1] = temp;
21+
};
22+
23+
let noBanished = 0;
24+
for (let i = 0; i < nums.length; i++) {
25+
if (nums[i] === val) {
26+
if (noBanished > nums.length) {
27+
break;
28+
}
29+
banishToTheEndOfTheArray(i);
30+
noBanished++;
31+
i--;
32+
}
33+
}
34+
35+
for (let i = 0; i < nums.length; i++) {
36+
if (nums[i] === val) {
37+
return i;
38+
}
39+
}
40+
41+
return nums.length;
42+
};
43+
44+
const arr = [2, 2, 3];
45+
46+
console.log(removeElement(arr, 3));
47+
console.log(arr);

0 commit comments

Comments
 (0)