Leetcode刷题笔记——27Remove Element

一、Problem

Given an array nums and a value val, 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 1:

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

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

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

二、Solution

给定一个数组nums和一个值val,原地移除val值并返回数组nums新的长度,不能开辟额外空间,数组元素的顺序可以被打乱。

思路1:

设置索引k指向数组首位,遍历数组nums,如果索引i指向的当前元素不等于val值,则将当前元素赋值给k指向的位置 然后k向后移一位,直到数组全部遍历完毕。

此时[0 k)区间为非val元素,返回索引k则为非val元素个数(索引值是从0开始的)

c++代码

class Solution {
public:
    int remove(vector<int> nums, int val) {
        int k = 0;   //定义个索引k 初值为数组首位
        //遍历数组 使[0 k)区间为非val元素  
        for (int i = 0; i < nums.size(); i++) 
            if (nums[i] != val)   
                nums[k++] = nums[i];
        return k;  // 返回索引值
    }

};

思路2:

代码参考:https://github.com/liuyubobobo/Play-Leetcode

本博客为博主的学习笔记,不作任何商业用途。
原文地址:https://www.cnblogs.com/guo7533/p/10421849.html