Skip to content

Commit 959dd36

Browse files
authored
Create 027. Remove Element
1 parent d297bef commit 959dd36

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

027. Remove Element

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

0 commit comments

Comments
 (0)