forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0027-remove-element.js
55 lines (46 loc) · 1.05 KB
/
0027-remove-element.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
52
53
54
55
/**
* Time O(N) | Space O(1)
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let ptr1 = nums.length - 2;
let ptr2 = nums.length - 1;
if(!nums) return 0;
if(nums.length === 1) {
if(nums[0] === val) return 0;
return 1;
}
while(ptr1 > -1) {
if(nums[ptr2] === val) {
ptr2--;
while(nums[ptr1] === val) {
ptr2--;
ptr1--;
}
}
else if(nums[ptr1] === val) {
let temp = nums[ptr1];
nums[ptr1] = nums[ptr2];
nums[ptr2] = temp;
ptr2--;
}
ptr1--;
}
return ptr2 + 1;
};
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
for(let i = 0; i < nums.length; i++) {
if(nums[i] === val) {
nums.splice(i, 1);
i--;
}
}
return nums.length;
};