-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveElement.java
More file actions
41 lines (36 loc) · 1010 Bytes
/
removeElement.java
File metadata and controls
41 lines (36 loc) · 1010 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
30
31
32
33
34
35
36
37
38
39
40
41
/*
Remove Element
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.
*/
// overwrite the target elem
public class Solution {
public int removeElement(int[] A, int elem) {
if(A==null || A.length==0) return 0;
int l=A.length;
int index=0;
for(int i=0; i<l; i++){
if(A[i] !=elem){
A[index++]=A[i];
}
}
return index;
}
}
// swap target elem to the end of the array
public class Solution {
public int removeElement(int[] A, int elem) {
if (A==null || A.length==0) return 0;
int i=0, j=A.length-1;
while (i <= j){
if (A[i] == elem) swap(A, i, j--);
else i++;
}
return j+1;
}
public void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}