Remove Element--LeetCode
来源:互联网 发布:fifa online3数据库16 编辑:程序博客网 时间:2024/06/06 08:59
1.题目
Remove Element
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.
2.题意
移除数组中等于val的元素,并返回新数组的长度
3.分析
1)遍历数组,将不等于val的值放回原数组
注意此前已经++index;所以最后return index;即可,不需要return index + 1;
2)每找到一个等于val的元素,将数组末尾的数移到该位置
这样可以保证如果没有重复就没有写操作
3)借助STL也可以AC,但不推荐
4.代码
1)
class Solution {public: int removeElement(vector<int>& nums, int val) { if(nums.size() == 0) return 0; int index = 0; for(int i = 0; i < nums.size(); ++i) { if(nums[i] != val) { nums[index] = nums[i]; ++index; } } return index; }};
2)
class Solution {public: int removeElement(vector<int>& nums, int val) { int len = nums.size(); if(len == 0) return 0; for(int i = 0; i < len; ++i) { if(nums[i] == val) { --len; nums[i] = nums[len]; --i; } } return len; }};
3)
class Solution {public: int removeElement(vector<int>& nums, int val) { if(nums.size() == 0) return 0; return distance(nums.begin(), remove(nums.begin(), nums.end(), val)); }};
阅读全文
0 0
- LeetCode:Remove Element
- LeetCode: Remove Element
- [Leetcode] Remove Element
- LeetCode: Remove Element
- leetcode 39: Remove Element
- [LeetCode] Remove Element
- Leetcode: Remove Element
- Leetcode:Remove Element
- Leetcode:Remove Element
- Leetcode:Remove Element
- [LeetCode]Remove Element
- LeetCode-Remove Element
- LeetCode - Remove Element
- LeetCode | Remove Element
- leetcode之Remove Element
- LeetCode - Remove Element
- LeetCode: Remove Element
- 【LeetCode】Remove Element
- bzoj1101 [POI2007]ZAP-Queries(莫比乌斯反演)
- mac安装mysql的两种方法(含配置)
- RecyclerView的使用(一)
- Centos7 安装与部署单实例oracle数据库
- [搜索 meet in the middle+哈希] ProjectEuler 598. Split Divisibilities
- Remove Element--LeetCode
- 创建oracle数据库表空间和用户
- 创建一个分布式网络爬虫的例子
- eclipse创建maven风格的web项目
- java学习.二位数组的遍历
- 687. Longest Univalue Path
- java.util.ConcurrentModificationException
- matplotlib.pyplot官方翻译教程
- Git分支管理的基本操作