小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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.

分析

这是一道很简单的题目,对数组进行一次遍历,删除与给定值相等的关键字,返回新长度即可。

AC代码

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int i = 0 , k = 0;
        while (i < nums.size())
        {
            if (nums[i] != val)
                nums[k++] = nums[i];
            i++;
        }
        return k;
    }
};

GitHub测试程序源码

posted on 2015-08-12 16:50  Coding菌  阅读(123)  评论(0编辑  收藏  举报