Skip to content

Commit 59b154d

Browse files
remove element in progress
1 parent efb79ed commit 59b154d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

EASY/src/easy/RemoveElement.java

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package easy;
2+
3+
import utils.CommonUtils;
4+
5+
/**27. Remove Element
6+
7+
Total Accepted: 135216
8+
Total Submissions: 384018
9+
Difficulty: Easy
10+
11+
Given an array and a value, remove all instances of that value in place and return the new length.
12+
13+
Do not allocate extra space for another array, you must do this in place with constant memory.
14+
15+
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
16+
17+
Example:
18+
Given input array nums = [3,2,2,3], val = 3
19+
20+
Your function should return length = 2, with the first two elements of nums being 2.*/
21+
public class RemoveElement {
22+
public int removeElement(int[] nums, int val) {
23+
for(int i = 0; i < nums.length; i++){
24+
int start = i;
25+
while(i < nums.length && nums[i] == val){
26+
i++;
27+
}
28+
if(i == nums.length) i--;
29+
nums[start] = nums[i];
30+
}
31+
CommonUtils.printArray(nums);
32+
return 0;
33+
}
34+
35+
public static void main(String...strings){
36+
RemoveElement test = new RemoveElement();
37+
int[] nums = new int[]{3,2,2,3};
38+
int val = 3;
39+
test.removeElement(nums, val);
40+
}
41+
}

0 commit comments

Comments
 (0)