[LeetCode] Remove Element 移除元素
2015-06-29 08:54
519 查看
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
这道题让我们移除一个数组中和给定值相同的数字,并返回新的数组的长度。是一道比较容易的题,我们只需要一个变量用来计数,然后遍历原数组,如果当前的值和给定值不同,我们就把当前值覆盖计数变量的位置,并将计数变量加1。代码如下:
LeetCode All in One 题目讲解汇总(持续更新中...)
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
这道题让我们移除一个数组中和给定值相同的数字,并返回新的数组的长度。是一道比较容易的题,我们只需要一个变量用来计数,然后遍历原数组,如果当前的值和给定值不同,我们就把当前值覆盖计数变量的位置,并将计数变量加1。代码如下:
class Solution { public: int removeElement(vector<int>& nums, int val) { int res = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] != val) nums[res++] = nums[i]; } return res; } };
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- 《C++ Primer Plus》学习笔记10
- C++面试题三
- 图片获得焦点变大并显示在最前方,覆盖后面的图片
- memcached 在maven项目中使用
- 如何为你的代码选择一个开源协议
- 开头决胜武器:软文开头的4种常用写法
- HDU2093--考试排名
- EF 实体+ Newtonsoft.Json 输出JSON 时动态忽略属性的解决方法
- 常程的ZUK手机有戏吗?
- 128.删除一维数组中相同的数
- [华为上机练习题]7.删除字符串中出现次数最少的字符
- [LeetCode] Implement strStr() 实现strStr()函数
- [转载] Go语言并发之美
- How to use API doc(demo) to create s square rectangle?
- windows下,python基于SocketServer模拟实现SSH(多线程版)
- struts2中非表单标签的使用 componen
- java集合类之------Properties
- 开源 java CMS - FreeCMS2.3会员头像设置
- 当大数据遇到安全分析
- 类别