Remove Element

来源:互联网 发布:javascript与jsp 编辑:程序博客网 时间:2024/05/01 15:15
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.
刚看到题目,觉得挺简单,但因为没有好好在脑子里面执行一遍,所以逻辑上有个小错误,把两个if顺序弄反了


int removeElement(int A[], int n, int elem) {int offset = 0;for (int i = 0; i < n; i++){if ( i-offset >= 0)//刚开始两个if搞错顺序了A[i-offset] = A[i];if (A[i] == elem)offset++;}return n - offset;}


0 0