LeetCode-027 Remove Element

来源:互联网 发布:mac os10.6.8镜像下载 编辑:程序博客网 时间:2024/06/05 19:14

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 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.

Analyse

题意为去除数组中值为val的数,要求空间复杂度为常数级。这道题跟026很像,只需要将上一道题的跟前面一个数相同的判断改成跟val相等即可,也是一道基础的题。这两道题主要想告诉我们怎么在不申请额外的空间,完成对数组的去重和去掉某个数。

Code

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int ans=0;        for (int i=0;i<nums.size();i++) {            if (nums[i]==val) ans++;            else nums[i-ans]=nums[i];        }        return nums.size()-ans;    }};
原创粉丝点击