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 };

 

posted @ 2013-10-30 14:14  移山测试工作室黑灯老师  阅读(540)  评论(0编辑  收藏  举报
count website visits
Buy Computers