(算法分析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
阅读全文
0 0
- (算法分析Week7)Remove Element[Easy]
- 算法第六周Remove Element[easy]
- 27. Remove Element [easy]
- Remove Element(easy)
- 27. Remove Element (Easy)
- (算法分析Week1)Majority Element[Easy]
- [Leetcode 27, easy] Remove Element
- <LeetCode><Easy> 28 Remove Element
- 27. Remove Element [easy] (Python)
- leetcode 27. Remove Element (EASY)
- Easy 27题 Remove Element
- 27. Remove Element 难度:easy
- Assign Cookies(算法分析week7)
- [LeetCode] Remove Element 分析
- 算法系列-Remove Element
- (算法分析Week9)Remove Duplicates from Sorted Array[Easy]
- [LeetCode] 027. Remove Element (Easy) (C++)
- 【LeetCode】2(7)Remove Element(Easy)
- 线性表综合试验(间接寻址)
- Java day6
- 数据类型bigint int smallint 和tinyint的区别
- bzoj2396 神奇的矩阵
- 持续集成与灰度发布
- (算法分析Week7)Remove Element[Easy]
- xcode Build Phases 增加新内容;SDL2 renderer already associated with window 错误
- IT男如何护肤?上班族男性护肤的方法有哪些?[图]
- Redis存储
- sublime 3 注册码
- SpringMVC的Controller和Struts2的Action的区别
- 顺序栈的实现
- RabbitMQ 详解
- 作业