Skip to content

Commit cc3f1fe

Browse files
committed
leetcode: remove element
1 parent 869b8f6 commit cc3f1fe

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package kent.alg.leetcode.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+
Your function should return length = 2, with the first two elements of nums being 2.
13+
It doesn't matter what you leave beyond the returned length.
14+
15+
16+
17+
* @author kentfan
18+
*
19+
*/
20+
public class RemoveElement {
21+
22+
public int removeElement(int[] nums, int val) {
23+
24+
int i = 0;
25+
for(int j=0; j<nums.length; j++) {
26+
27+
if(nums[j] != val) {
28+
29+
nums[i] = nums[j];
30+
i++;
31+
}
32+
33+
}
34+
return i;
35+
}
36+
37+
public static void main(String[] args) {
38+
// TODO Auto-generated method stub
39+
40+
}
41+
42+
}

0 commit comments

Comments
 (0)