LeetCode(027) Remove Element (Java)

题目如下:

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;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值