您的位置:首页 > 编程语言 > C语言/C++

leetcode27题 题解 翻译 C语言版 Python版

2016-04-15 09:43 197 查看
27. Remove Element

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.

Hint:

Try two pointers.
Did you use the property of "the order of elements can be changed"?
What happens when the elements to remove are rare?

27.移除元素
给定一个数组和一个值,就地移除所有等于这个值的数组元素并返回新的数组长度。
不要分配内存创建另外的数组,你必须用恒定的内存就地完成。
元素的顺序可以被改变,你不用管在新长度之外数组剩下的元素值。
举例:
给定一个数组nums=[3,2,2,3],val=3
你的函数应该返回length=2,而且nums的前两个元素值应该都为2
提示:
1.尝试用两个指针
2.你用了元素顺序可以改变的特性了吗?
3.当需要移除的元素很少时会发生什么?

思路:由于不需要考虑数组元素相对顺序,所以只需要从前向后遍历,遇到不等于val的元素就将数组尾部的元素移过来覆盖他即可。因为最后超过新数组长度的元素不用管,所以我们可以实时变化新数组长度,这样也能实时表示最后一个可以移过来的元素。需要注意数组只有一个元素并且要移除这个元素时要处理到位,所以第一个指针指向当前元素,第二个指针也即新数组长度表示的应该指向最后一个元素的后面一个位置。

int removeElement(int* nums, int numsSize, int val) {
int n = numsSize, i = 0;
while(i < n){
if (nums[i] == val){
nums[i] = nums[(n--) - 1];
}
else i++;
}
return n;
}


class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
n, i = len(nums), 0
while i < n:
if nums[i] == val:
nums[i] = nums[n - 1]
n -= 1
else:
i += 1
return n
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: