移除元素

117 阅读1分钟

移除元素

27 移除元素

题解一(暴力解法):

class Solution {
    public int removeElement(int[] nums, int val) {
        int length = nums.length;
        for(int i = 0; i < length; i++) {
            if(nums[i] == val) {
                //数组当前索引值等于val值时,说明当前索引值需要一处,数组元素整体前移,覆盖当前索引值
                for(int j = i + 1; j < length; j++) {
                    nums[j -1] = nums[j];
                }
                //由于数组元素前移后,下标i后的值都往前移动了一位,因此i也要向前移动一位
                i --;
                //数组长度减1
                length --;
            }
        }
        return length;
    }
}

题解二(双指针法):

class Solution {
    public int removeElement(int[] nums, int val) {
        //慢指针一方面控制val的值个数,另一方面控制消除元素的位置
        int slowindex = 0;
        for (int fastindex = 0; fastindex < nums.length; fastindex++) {
            if( nums[fastindex] != val) {
                nums[slowindex++] = nums[fastindex]; 
            }
        }
        return slowindex;
    }
}