Skip to content

Commit ee608ed

Browse files
committed
remove-element
1 parent 43ec9a4 commit ee608ed

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

easy/0027 remove-element/readme.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Remove Duplicates from Sorted Array
2+
3+
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
4+
5+
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
6+
7+
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
8+
9+
## Example 1
10+
11+
Given nums = [3,2,2,3], val = 3,
12+
13+
Your function should return length = 2, with the first two elements of nums being 2.
14+
15+
It doesn't matter what you leave beyond the returned length.
16+
17+
## Example 2
18+
19+
Given nums = [0,1,2,2,3,0,4,2], val = 2,
20+
21+
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
22+
23+
Note that the order of those five elements can be arbitrary.
24+
25+
It doesn't matter what values are set beyond the returned length.
26+
27+
## Clarification
28+
29+
Confused why the returned value is an integer but your answer is an array?
30+
31+
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
32+
33+
Internally you can think of this:
34+
35+
// nums is passed in by reference. (i.e., without making a copy)
36+
int len = removeDuplicates(nums);
37+
38+
// any modification to nums in your function would be known by the caller.
39+
// using the length returned by your function, it prints the first len elements.
40+
for (int i = 0; i < len; i++) {
41+
print(nums[i]);
42+
}
43+
44+
## More info
45+
46+
<https://leetcode.com/problems/remove-element/>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} val
4+
* @return {number}
5+
*/
6+
var removeElement = function(nums, val) {
7+
let i=0;
8+
for(let j=0;j<nums.length;j++){
9+
if(nums[j]!=val){
10+
nums[i] = nums[j];
11+
i++;
12+
}
13+
}
14+
return i;
15+
};
16+
17+
var removeElement = function(nums, val) {
18+
for(var i = nums.length - 1; i >= 0; i--){
19+
if(nums[i] === val){
20+
nums.splice(i, 1);
21+
}
22+
}
23+
return nums.length
24+
};
25+
26+
console.log(removeElement([0,1,2,2,3,0,4,2],2))

0 commit comments

Comments
 (0)