-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveElement.java
More file actions
63 lines (59 loc) · 1.12 KB
/
RemoveElement.java
File metadata and controls
63 lines (59 loc) · 1.12 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class RemoveElement {
/*
public int removeElement(int[] A, int elem) {
int len = A.length;
if (len == 0) {
return 0;
}
for (int i = 0; i < len; i++) {
if (A[i] == elem) {
while (len > i && A[len - 1] == elem) {
len--;
}
if (len == i) {
return len;
}
A[i] = A[len - 1];
len--;
}
}
return len;
}
*/
public int removeElement(int[] A, int elem) {
int len = A.length;
if (len == 0) {
return 0;
}
int offset = 0;
for (int i = 0; i < len - offset; i++) {
System.out.println("i = " + i + "; offset = " + offset);
A[i] = A[i + offset];
if (A[i] == elem) {
int j = i + 1 + offset;
offset++;
while (j < len && A[j] == elem) {
j++;
offset++;
}
if (j == len) {
return len - offset;
}
A[i] = A[j];
}
}
//printArr(A);
return len - offset;
}
public void printArr(int[] A) {
for (Integer x : A) {
System.out.print(x + " ");
}
System.out.print("\n");
}
public void testRemove() {
int[] A = {0,4,4,0,4,4,4,0,2};
System.out.println( removeElement(A, 4));
printArr(A);
}
}