27. Remove Element

来源:互联网 发布:angularjsmin.js 编辑:程序博客网 时间:2024/06/04 23:56


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.

Show Hint 

    先翻译下题目:题目要求对给定的数据移除特定的数然后返回新数组的长度;要求是不能额外创建新的数组;

    我们先看看如果是创建新的数组的话,那就很简单了:

    设置两个游标i,j,初始化它们为0.。然后用i去遍历给定的数组nums:

    1.当遍历到与给定值不等的元素时,将该元素的值赋值给新的数组newnums的下一个元素(此处用j记录新数组的下一个空位置的坐标),然后j++;

    2.当遍历到与给定值相等的元素时,继续遍历下一个,i++,不对j进行任何操作;

    则当nums遍历完成后,新的移除了特定值val的数组生成,同时j的值即是新数组的长度;

    而题目要求不能创建新的数组,那我们就在原先的数组上面进行整个赋值操作即可;

    这里我的思路是设置一个记录数组长度的数i以及一个用于新赋值的游标j,初始时i,j为0,然后对整个数组进行一次遍历:

    1.遍历到与给定值相等的数组元素时,j的值保持不变;

    2.遍历到与给定值不相等的数组元素时,给元素nums[j]赋值当前遍历到的数组元素,然后j++;

    以下为代码示例:

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



    0 0