27. Remove Element
来源:互联网 发布:angularjsmin.js 编辑:程序博客网 时间:2024/06/04 23:56
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.
Show Hint先翻译下题目:题目要求对给定的数据移除特定的数然后返回新数组的长度;要求是不能额外创建新的数组;
我们先看看如果是创建新的数组的话,那就很简单了:
设置两个游标i,j,初始化它们为0.。然后用i去遍历给定的数组nums:
1.当遍历到与给定值不等的元素时,将该元素的值赋值给新的数组newnums的下一个元素(此处用j记录新数组的下一个空位置的坐标),然后j++;
2.当遍历到与给定值相等的元素时,继续遍历下一个,i++,不对j进行任何操作;
则当nums遍历完成后,新的移除了特定值val的数组生成,同时j的值即是新数组的长度;
而题目要求不能创建新的数组,那我们就在原先的数组上面进行整个赋值操作即可;
这里我的思路是设置一个记录数组长度的数i以及一个用于新赋值的游标j,初始时i,j为0,然后对整个数组进行一次遍历:
1.遍历到与给定值相等的数组元素时,j的值保持不变;
2.遍历到与给定值不相等的数组元素时,给元素nums[j]赋值当前遍历到的数组元素,然后j++;
以下为代码示例:
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i=0;
int j=0;
for(i=0;i<nums.size();i++){
if(nums[i]==val)
{
continue;
}
nums[j]=nums[i];
j++;
}
return j;
}
};
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- 27.Remove Element
- [Leetcode] 27.Remove Element
- 27. Remove Element
- 27. Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- 27. Remove Element
- 27. Remove Element
- 27. Remove Element
- Leetcode 27. Remove Element
- 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 27. Remove Element
- The CUDA error code was: CUDA_ERROR_NO_BINARY_FOR_GPU
- 程序员轻松一刻!
- yii2如何写一个类来统一处理url?
- 设计模式(十五):原型模式
- mongodb用户权限修改,删除以及robomongo显示问题
- 27. Remove Element
- Android线程池
- mshta usage
- DIY个人智能家庭网关—— python篇之获取路由器外网地址
- java中char.At怎么用?
- javascript对象的创建和继承实现
- 使用WindowsAPI取剪贴板文本
- codeforces 371C 二分
- 北大 C++ 2.6 构造函数