[LeetCode] Remove Element 移除元素

Grandyang發表於2015-06-29

 

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.

 

這道題讓我們移除一個陣列中和給定值相同的數字,並返回新的陣列的長度。是一道比較容易的題,我們只需要一個變數用來計數,然後遍歷原陣列,如果當前的值和給定值不同,我們就把當前值覆蓋計數變數的位置,並將計數變數加1。程式碼如下:

 

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

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章