您的位置:首页 > 编程语言 > Java开发

LeetCode(027) Remove Element (Java)

2015-04-12 02:36 309 查看
题目如下:

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.

分析如下:

两种办法:

第一种: 想象成把原数组A的元素依次诺入到新数组B中,必然有B的长度小于A的长度,因为可以利用在A当做B来用。

第二种: 把不需要的元素扔到原数组尾部。

我的代码:

//第一种 212ms
public class Solution {
    public int removeElement(int[] A, int elem) {
        //{1,1,2,1,2,3,2,3,1}
        int newIndex = 0;
        for (int oldIndex = 0; oldIndex < A.length; ++oldIndex) {
            if (A[oldIndex] != elem) {
                A[newIndex++] = A[oldIndex];
            } 
        }
        return newIndex;
    }
}


//第二种 218 ms
public class Solution {
    public int removeElement(int[] A, int elem) {
        if (A.length ==0) return A.length;
        //if (A.lenth == 1 && A[0] == elem) return 0;
        //if (A.lenth == 1 && A[0] != elem) return 1;
        int i = 0, j = A.length - 1;
        //while (i < j) {
        while (i <= j) {
            if (A[i] == elem) {
                int tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
                --j;
            } else {
                ++i;
            }
        }
        //return j; 因为while (i<=j)才结束,而不是while (i < j)才结束,所以这里返回j+1
        return j + 1;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: