```
int removeElement(int* nums, int numsSize, int val) {
int tail, i, j;
tail = numsSize - 1;
for (i = 0; i <= tail; i++) {
if (nums[i] != val) {
continue;
}
// find the last available element
for (j = tail; j > i; j--) {
if (nums[j] != val) {
break;
}
}
if (j == i) {
return i; // cannot find
}
nums[i] = nums[j];
tail = j - 1;
}
return i;
}
```