@CrazyHenry
2018-01-03T18:32:24.000000Z
字数 1366
阅读 1118
ddddLeetcode刷题
- Author:李英民 | Henry
- E-mail: li
_
yingmin@
outlookdot
com- Home: https://liyingmin.wixsite.com/henry
快速了解我: About Me
转载请保留上述引用内容,谢谢配合!
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.
Example:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure.
//Author: Li_Yingmin@https://liyingmin.wixsite.com/henry
//Email: li_yingmin@outlook DOT com
//Leetcode-27
//T(n)=O(n), S(n)=O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if(nums.size()<1) return 0;
for(auto it = nums.begin(); it != nums.end(); ++it)
{
if(*it == val)
{
nums.erase(it);
--it;
}
}
return nums.size();
}
};
// LeetCode, Remove Element
// T(n)=O(n),S(n)=O(1)
class Soluntion
{
public:
int removeElement(vector<int>& nums, int val)
{
return distance(nums.begin(), remove(nums.begin(), nums.end(), val));
}
};
class Solution
{
public:
int removeElement(vector<int>& nums, int target)
{
int index = 0;
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i] != target)
{
nums[index++] = nums[i];
}
}
return index;
}
};