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++实现:
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 27 Remove Element (C,C++,Java,Python)
- LeetCode 35 — Search Insert Position(C++ Java Python)
- leetcode_[python/java/javascript/C++]_401_Binary Watch(二进制手表)
- leetcode-java-27. Remove Element
- [LeetCode] 003. Longest Substring Without Repeating Characters (Medium) (C++/Java/Python)
- [LeetCode] 011. Container With Most Water (Medium) (C++/Java/Python)
- [LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)
- LeetCode 66 — Plus One(C++ Java Python)
- [LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)
- 【C++】【LeetCode】27. Remove Element
- LeetCode 50 — Pow(x, n)(C++ Java Python)
- LeetCode 136 — Single Number(C++ Java Python)
- LeetCode 69 — Sqrt(x)(C++ Java Python)
- LeetCode 64 — Minimum Path Sum(C++ Java Python)
- 【LeetCode 27】Remove Element(Python)
- [LeetCode] 004. Median of Two Sorted Arrays (Hard) (C++/Java/Python)
- LeetCode 88 — Merge Sorted Array(C++ Java Python)
- LeetCode 5 Longest Palindromic Substring(C,C++,Python,Java)
- LeetCode 58 — Length of Last Word(C++ Java Python)
- LeetCode 21 — Merge Two Sorted Lists(C++ Java Python)