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.

分析:题意是要求从给定的数组中移除给定元素。
改题简单,基本思路是:直接将除给定元素外其他元素直接放到新的数组(泛型)里,直接一个for循环加判断就可以解决。
java代码: Accepted

    //Special case
        if(nums == null || nums.length == 0)
            return 0;
        //Normal case
        for(int i = 0;i < nums.length;i ++){
            if(val != nums[i]){
                list.add(nums[i]);
            }
        }

        for(int i = 0;i < list.size();i ++){
            nums[i] = list.get(i);

        }
        return list.size();

上述方法很直接,但是如果题意要求不能新开空间,那么如何做呢?
基本思路,在原来的数组上做文章,将给定元素直接移除,把其他元素直接覆蓋到给定元素的位置,重构数组。如图示意:
《LeetCode解题报告--Remove Element》

利用“双指针”i,j,i指向“新数组”的序号,j用于寻找不等于给定元素的元素,当遇到非给定元素是“指针”i,j同时移动,否则,只有j移动,直到遍历最后。

Java代码: Acdepted

public class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        int j = 0;
        while(j < nums.length){
            if(nums[j] != val){
                nums[i] = nums[j];
                i ++;
            }
            j ++;
        }
        //System.out.println(Arrays.toString(nums));
        return i;
    }

}
点赞