LeetCode 27. Remove Element

来源:互联网 发布:mac桌面双桌面用 编辑:程序博客网 时间:2024/06/06 13:15

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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:

Given nums = [3,2,2,3], val = 3,Your function should return length = 2, with the first two elements of nums being 2.

移除数组中和给定值相同的元素,返回新数组的长度。不允许分配新的空间来制造新的数组,数组元素的顺序可以改变,新数组长度外的元素不需要理会。
这题还是用Two Pointers,一个指向数组当前尾元素(end),一个指向当前元素(i),若当前元素不等于给定值,那么i移到下一个元素;若当前元素等于给定值,就把尾元素的值赋给当前元素,并把end指针向前移一位。

int removeElement(vector<int>& nums, int val) {        if (nums.size() == 0) return 0;        int end = nums.size() - 1, i = 0;        while (i <= end)        {            if (nums[i] == val) {                nums[i] = nums[end];                --end;            }            else ++i;        }        return i;    }