码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Remove Element (easy)

时间:2015-03-31 17:29:00      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

思路:

s记录下一个判断位置, e记录结束位置,把前面的待排除元素与后面要保留的元素互换。

int removeElement(int A[], int n, int elem) {
    int s = 0, e = n - 1;
    while(s <= e)
    {
        if(A[e] == elem) //末尾待删 直接删除
        {
            e--;
            continue;
        }
        if(A[s] == elem)
        {
            A[s++] = A[e--];
        }
        else
        {
            s++;
        }
    }
    return e + 1;
}

 

【leetcode】Remove Element (easy)

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4381269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!