您的位置:首页 > 其它

[leetcode]27 Remove Element

2018-03-19 22:48 302 查看

[leetcode]27 Remove Element

转载记得注明出处哦~

Analysis

很久很久很久没刷题,我以为寒假我会刷题,但是并没有可以说是很放肆了,然后呢最近因为采访一个拿到offer的学长,学长说刷题很重要!!所以决定题还是要刷的。另外学长也超帅的,哇,对大神总是有一种崇拜 —— [ 莫名其妙的心情记录hiahia~ ]

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 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.

其实题目很简单啦,就是给定一个数组,然后再给出一个数值val,要求就是删掉这个数组中等于val的数,然后返回新数组的大小。按道理讲,我在最开始定义一个值cnt,然后遍历数组,每次遇到不等于val的就把cnt+1,最后返回cnt的值就好了,但是运行的时候,看结果好像不行,他好像除了检测cnt的值,还会检测删掉之后的新数组。(我也不知道分析的对不对,如果有大神搞懂了为啥只返回cnt的值不对,可以帮忙指出来哦~)所以光记录cnt是不行的,还是要对数组进行操作。同时题目要求空间复杂度为O(1),所以不能另开数组,只能用原数组,具体怎么实现还是看代码吧~

implement(c++)

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int cnt=0;
for(int i=0; i<nums.size();i++)
{
if(nums[i]!=val)
nums[cnt++]=nums[i];
}
return cnt;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: