leetcode-algorithms-27 Remove Element

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.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

解法

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

链接: leetcode-algorithms 目录

最新文章

  1. input-placeholder
  2. Microsoft.Office.Interop.Excel的用法
  3. 取得Android平台某设备上所有可用的Sensors
  4. php练习2——乘法表,变量的使用
  5. 项目属性--&gt;生成事件--&gt;后期生成事件命令行
  6. linux下系统定时任务配置----crontab(mysql定时备份)
  7. Linux下同步工具inotify+rsync使用详解
  8. phpstorm9如何配置interpreter
  9. SPOJ-ANTP [组合数学]
  10. 第一个asp.net实例——生日邀请以及回函
  11. 分布式代码管理系统Git实践
  12. webpacke踩坑-新手
  13. openssl enc(对称加密)
  14. Condition线程通信(七)
  15. Kolmogorov–Smirnov test(KS)
  16. ABBYY Cup 3.0G3. Good Substrings
  17. ubuntu 16.04下使用 python pip的安装问题。
  18. Ubuntu/Linux网络配置常用命令
  19. 第75讲:模式匹配下的For循环
  20. A Creative Cutout CodeForces - 933D (计数)

热门文章

  1. Deep Learning framework --- MexNet 安装,测试,以及相关问题总结
  2. Visual studio 离线安装
  3. Jupyter Notebook主题字体设置及自动代码补全
  4. spring与mybatis四种整合方法
  5. pom中配置的仓库无效的问题
  6. http_load 高并发测试
  7. Integer的最大值
  8. System.out.println 报错: 只能运行在方法体内哦, 类里面只包含属性和方法哦,注意!
  9. AndroidImageSlider第一张图闪过的问题解决
  10. (转)C# Xml进行序列化与反序列化