-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path27.remove-element.js
59 lines (48 loc) · 1.49 KB
/
27.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
56
57
58
59
/*
* @lc app=leetcode id=27 lang=javascript
*
* [27] Remove Element
*/
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
/*
splice is functions has side effect,the returned val is an array that include the delete val
one of the challenging in this question is looping and changing the length of the array
https://coderwall.com/p/prvrnw/remove-items-from-array-while-iterating-over-it
O(n for looping the entire arr)
* O(n) for removing 1 elements, causing elements after deleted element to moves to left
*/
/*
* @lc app=leetcode id=27 lang=javascript
*
* [27] Remove Element
*/
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
/*
splice is functions has side effect,the returned val is an array that include the delete val
one of the challenging in this question is looping and changing the length of the array
https://coderwall.com/p/prvrnw/remove-items-from-array-while-iterating-over-it
O(n for looping the entire arr)
* O(n) for removing 1 elements, causing elements after deleted element to moves to left
*/
var removeElement = function (nums, val) {
/* pure o(N) */
if (nums == null || nums.length == 0) {
return 0;
}
let newLength = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[newLength++] = nums[i];
}
}
return newLength;
};
//for 3,2,2,3, it returns 2, but remember the nums is 2,2,2,3, that why if you want to further splice it with length, if you want to get the removed element