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

LeetCode 27 — Remove Element(C++ Java Python)

2014-02-23 15:54 661 查看
题目: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
        感谢阅读,欢迎评论!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode