leetcode: Remove Element
http://oj.leetcode.com/problems/remove-element/
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.
思路:
和Remove Duplicates from Sorted Array类似,当已经删除n个元素后,需要保留的元素必须往前移动n步。
1 class Solution { 2 public: 3 int removeElement(int A[], int n, int elem) { 4 int len = n, step = 0; 5 6 for (int i = 0; i < n; ++i) { 7 if (A[i] != elem) { 8 if (step > 0) { 9 A[i - step] = A[i]; 10 } 11 } 12 else { 13 ++step; 14 --len; 15 } 16 } 17 18 return len; 19 } 20 };