leetcode 39: Remove Element
2013-01-16 09:06
288 查看
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.
//this approach can keep the original order.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
class Solution { public: int removeElement(int A[], int n, int elem) { // Start typing your C/C++ solution below // DO NOT write int main() function int i=0, j=n-1; while( i<=j) { if( A[i] == elem) { while( j>=i && A[j] == elem ) j--; if( j<= i ) break; A[i] = A[j--]; } i++; } return i; } };
public class Solution { public int removeElement(int[] A, int elem) { //113251631345465, 1 //check input. if(A==null || A.length<1) return 0; int i=-1; for(int j=0; j<A.length; j++) { if(A[j]!=elem) { A[++i] = A[j]; } } return i+1; } }
//this approach can keep the original order.
class Solution { public: int removeElement(int A[], int n, int elem) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int i=-1, j=0; while(j<n) { if(A[j]!=elem) { A[++i] = A[j++]; } else { ++j; } } return i+1; } };
相关文章推荐
- leetcode 39: Remove Element
- 【LeetCode】118_Pascal's Triangle
- 【Leetcode】27. Remove Element
- leetcode:pascal's_triangle_II
- Leetcode: Remove Element
- [LeetCode] Remove Element (三种解法)
- LeetCode(Oct30'12):Triangle 数字三角形
- [Leetcode 39] 129 Sum Root to Leaf Numbers
- [LeetCode] Remove Element
- Leetcode-Remove Element
- LeetCode-27-Remove Element(C语言实现)
- leetcode 27:Remove Element
- leetcode Pascal's Palindrome 2
- LeetCode OJ Pascal's Triangle
- LeetCode :: Remove Element
- 【LeetCode】Remove Element
- LeetCode:27. Remove Element
- LeetCode 27 Remove Element
- [leetcode][two pointers] Remove Element
- Leetcode 27. Remove Element