Leetcode: 27. Remove Element

Description

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example

Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

思路

  • 这个问题同26类似问题
  • 一个下标为去除指定元素后的索引,一个下标是原数组的索引

代码

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int len = nums.size();
        if(len == 0) return len;
        
        int s = -1, i = 0;
        while(i < len){
            if(nums[i] == val){
                ++i;
                continue;
            }
            
            nums[++s] = nums[i++];
        }
        
        return s + 1;
    }
};
posted @ 2017-05-08 10:29  JeffLai  阅读(120)  评论(0编辑  收藏  举报