本文共 820 字,大约阅读时间需要 2 分钟。
问题:
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.
解答:先排序,后设定两个指针,first指向第一个等于elem的位置,last指向first之后,第一个不等于elem的元素。
first和last之间就是重复的元素elem。
重点注意:
1 因为第一步是寻找数组中等于elem的第一个位置,如果数组中没有该元素,需要特别的处理。
2 如果输入的数组大小为0,直接返回0.
代码:
class Solution {public: int removeElement(int A[], int n, int elem) { if(n == 0) return 0; sort(A, A+n); int first,last; first = 0; while(A[first] != elem) { ++first; if(first == n) return n; } last = first; while(A[last] == elem) ++last; while(last != n) A[first++] = A[last++]; return n - (last - first); }};
转载地址:http://vktsi.baihongyu.com/