- 题目
Given an array nums and a value val, 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 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
1. c++版本
思想, 最简单最直观的想法,就是相等的时候直接删除,注意c++
erase
用法
int removeElement(vector<int>& nums, int val) {
for (int i=0; i<nums.size(); ++i) {
if (nums[i] == val) {
nums.erase(nums.begin()+i);
i--;
}
}
return nums.size();
}
优化版本, 注意题目说只要保证前面的顺序正确就可以了。由此,想到将要删除的元素,移动到数组后面。一步步替换。第1个删除元素->第1个非删除元素进行交换,第2个删除元素->第2个非删除元素进行交换,以此类推……
注意
:
(1) 数组为[]
(2) [1,2,3,4] val=4; [1,2,3,3] val =4; 需要考虑这种情况。此时需要判断最后一个元素是否为val
(3) [2,2,2,2] val =2; [1,2,2,2] val=2; [2,2,1] val=2
int removeElement(vector<int>& nums, int val) {
int i=0, j=i+1;
for (; j<nums.size(); ) {
if (nums[i] == val && nums[j] != val) {
swap(nums[i], nums[j]);
i++;
}
else if (nums[i] != val)
i++;
j++;
}
if (!nums.empty() && nums[nums.size()-1] != val)
return i+1;
return i;
}
2. python版本
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
index = 0
length = len(nums)
while index < length:
if nums[index] == val:
nums.remove(nums[index])
length = len(nums)
else:
index = index + 1
return len(nums)
同c++版本,python 优化版本.
注意 python list 中元素的交换。a,b=b=a
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
j = 1
while j < len(nums):
if nums[i] == val and nums[j] != val:
nums[i], nums[j] = nums[j], nums[i]
i = i+1
elif nums[i] != val:
i = i + 1
j = j+1
if nums and nums[-1] != val:
return i+1
return i
网友评论