首页 > 代码库 > Remove Element

Remove Element

https://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.

解题思路:

这题目巨坑爹,我看半天硬是没看懂什么意思。既然要求返回的只是length,那么直接减去==目标数值的数量不就可以了吗?可惜题目没说明的是,还要检查这个new length里面有没有这个目标value。我想也是这个题目含义比较ambiguous的地方。

public class Solution {    public int removeElement(int[] A, int elem) {        if(A.length == 0){            return 0;        }        int left = 0;        int right = A.length - 1;                while(left <= right){            if(A[left] == elem){                int temp = A[left];                A[left] = A[right];                A[right] = temp;                //这里直接A[left] = A[right]也可以,因为题目不要求后面的元素是啥                right--;            }else{                left++;            }        }        return right + 1;    }}

 另外还有其他两个解法,比我的代码更简单点。

public class Solution {    public int removeElement(int[] A, int elem) {        int count = 0;        for(int i=0; i<A.length; i++){            if(A[i] != elem){                A[count] = A[i];                count++;            }        }        return count;    }}
public class Solution {    public int removeElement(int[] A, int elem) {        int length = A.length;        int count = 0;        for(int i = 0 ; i < length; i++){            if(A[i] == elem){                count++ ;            }            else{                A[i-count] = A[i];            }        }        return length-count;    }}

http://www.cnblogs.com/EdwardLiu/p/3703444.html

http://blog.hushlight.com/2015/01/remove-element/

Remove Element