题目:http://oj.leetcode.com/problems/remove-element/
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
题目翻译:给定一个数组和一个值,就地删除该值的所有实例,并返回新的长度。
元素的顺序是可以改变的。除了新的长度外,留下啥都不要紧。
分析:
与上一篇博客的题目类似:Remove Duplicates from Sorted Array http://blog.csdn.net/lilong_dream/article/details/19757047
C++实现:
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int index = 0;
for(int i = 0; i < n; ++i)
{
if(A[i] != elem)
{
A[index] = A[i];
++index;
}
}
return index;
}
};
Java实现:
public class Solution {
public int removeElement(int[] A, int elem) {
int index = 0;
for(int num : A) {
if(num != elem) {
A[index] = num;
++index;
}
}
return index;
}
}
Python实现:
class Solution:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
index = 0
for num in A:
if num != elem:
A[index] = num
index += 1
return index
感谢阅读,欢迎评论!
本文介绍了一种在数组中删除指定值所有实例的方法,并提供了C++, Java和Python三种语言的实现方式。通过遍历数组并将非目标值元素向前移位,最终返回新的有效长度。
&spm=1001.2101.3001.5002&articleId=19759709&d=1&t=3&u=47e6a309a22d47c28a69a0c345a7d3b9)
1095

被折叠的 条评论
为什么被折叠?



