Skip to content

Commit 22a6574

Browse files
committed
solve one Q from array
1 parent 2bd19b0 commit 22a6574

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Array/day6.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// ! DSA in JavaScript day 5
2+
3+
// Todo: Topic Array
4+
5+
// * Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
6+
// * Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
7+
// * Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
8+
// * Return k.
9+
10+
// * input: --> [3,2,2,3], val = 3, output --> 2
11+
12+
// Todo: My Answer (Pass Just One Case)
13+
function removeElement(nums, val) {
14+
for (let i = 0; i < nums.length; i++) {
15+
if (nums[i] === val) {
16+
nums.splice(i, i);
17+
}
18+
}
19+
return nums.length;
20+
}
21+
const nums1 = [3, 2, 2, 3];
22+
const val1 = 3;
23+
console.log(removeElement(nums1, val1));
24+
25+
// Todo: Second Try (Accepted)
26+
function removeElement(nums, val) {
27+
let k = 0;
28+
for (let i = 0; i < nums.length; i++) {
29+
if (nums[i] !== val) {
30+
nums[k] = nums[i];
31+
k++;
32+
}
33+
}
34+
35+
return k;
36+
}
37+
38+
const nums = [3, 2, 2, 3];
39+
const val = 3;
40+
console.log(removeElement(nums, val));

0 commit comments

Comments
 (0)