-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveElement.java
45 lines (38 loc) · 1.03 KB
/
RemoveElement.java
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
42
43
44
45
/*
*Key point: consider boundry conditions, when A.length < 2 and i == j
*
*/
public class Solution {
public int removeElement(int[] A, int elem) {
//handle the condition the A.length < 2
if(A.length == 0)
return 0;
else if(A.length == 1){
if(A[0] == elem)
return 0;
else
return 1;
}
int len = 0;
int i = 0;
int j = A.length - 1;
//i==j is necessary to guarantee the correctness
while(i <= j){
if(A[i] != elem){
i++;
len++;
}
else{//consider A[i] == elem
if(A[j] != elem){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
i++;
len++;
}
j--;
}
}
return len;
}
}