forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path027RemoveElement.java
More file actions
29 lines (25 loc) · 887 Bytes
/
027RemoveElement.java
File metadata and controls
29 lines (25 loc) · 887 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Author: Li Long, [email protected]
// Date: Apr 17, 2014
// Source: http://oj.leetcode.com/problems/remove-element/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/19759709
// Given an array and a value,
// remove all instances of that value in place and return the new length.
// The order of elements can be changed.
// It doesn't matter what you leave beyond the new length.
public class RemoveElement {
public int removeElement(int[] A, int elem) {
int index = 0;
for(int num : A) {
if(num != elem) {
A[index] = num;
++index;
}
}
return index;
}
public static void main(String[] args) {
RemoveElement slt = new RemoveElement();
int[] A = new int[] { 1, 2, 4, 2, 5 };
System.out.println(slt.removeElement(A, 4));
}
}