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.
01 public int removeElement(int[] A, int elem) {
02 int last=A.length-1;
03 int i=0;
04 while(i<last)
05 {
06 if(A[i]==elem)
07 {
08 while(last>i&&A[last]==elem)
09 {
10
11 last--;
12 }
13 A[i]=A[last];
14 i++;
15 last--;
16 }
17 else
18 {
19 i++;
20 }
21 }
22 if(last>=0 && A[last]==elem)
23 last--;
24 return last+1;
25 }
02 int last=A.length-1;
03 int i=0;
04 while(i<last)
05 {
06 if(A[i]==elem)
07 {
08 while(last>i&&A[last]==elem)
09 {
10
11 last--;
12 }
13 A[i]=A[last];
14 i++;
15 last--;
16 }
17 else
18 {
19 i++;
20 }
21 }
22 if(last>=0 && A[last]==elem)
23 last--;
24 return last+1;
25 }
没有评论:
发表评论