题目
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.
题意
给你一个数组和一个值,将数组中所有等于这个值的数删除,形成新的数组。
要求:
- 不能使用新的数组。
- 只能使用连续的内存。
时间复杂度为O(n)。**
思路
题意很简单和26题思路完全一样。
http://blog.csdn.net/xunalove/article/details/77972021C++语言
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];
res+=1;
}
}
return res;
}
};
C++语言
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
res =0
for index in range(0,len(nums)):
if nums[index] != val:
nums[res]=nums[index]
res = res + 1
return res