leetcode之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记录下数组A的长度,其次对A中的元素开始遍历比较,如果A中的元素和ele相同,则将length减1

        int length = A.length;
        for(int i = 0;i<A.length;i++){
            if(A[i] == elem){
                length = length - 1;
            }
        }
        return length;        

提交之后出现了错误,我觉得最主要的原因可能是没有改变原来的数组,只是针对数组的长度变化。

修改之后:

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

提交成功,之后看了网上看了别人的方法,大部分人都是如果遇到elem,就将它调整到数组的后面去,

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

觉得它i和length处理那里很好,拿来借鉴。

原文地址:https://www.cnblogs.com/gracyandjohn/p/4381234.html