(算法分析Week7)Remove Element[Easy]

来源:互联网 发布:合肥晨飞网络 编辑:程序博客网 时间:2024/06/07 12:00

27.Remove Element

题目来源

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

Solution

在数组中,删除给定数值的元素。
思路很简单,遍历一次整个数组,当元素判断与给定数值相等时,将其后的元素向前移动。
*题目不允许增加新的空间,否则也可以考虑设置需删除的元素为特殊值,然后将非特殊值的数据存入新的数组中
这道题中,我用的是vector,直接可以利用erase函数,方便删除。
需要注意的是erase的用法,容易出现“野指针”的问题,具体可以参考vector::erase()方法的详细介绍及问题解答

Complexity analysis

O(n)
忽略erase具体操作。

Code

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int length = 0;        for (auto iter = nums.begin(); iter != nums.end(); ) {            if (*iter == val) {                iter = nums.erase(iter);            }            else iter++;        }        return nums.size();    }};

Result

这里写图片描述

原创粉丝点击