LeetCode题解 -- 双指针(27)

Remove Element

Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

时间复杂度:O(n)
空间复杂度:O(1)

public static int removeElement(int[] nums, int val) {

        int count = 0;
        int len = nums.length;
        int i = 0;
        while(i < len) {
            if(nums[i] == val) {
                count++;
            }else {
                int temp = nums[i];
                nums[i] = nums[i - count];
                nums[i - count] = temp;
            }
            i++;
        }
        
        return len - count;
    }

其实利用双指针,更好理解。
i,j 指针分别代表合法指针和遍历指针,只有j指向的数字 != val,才会将数字写入nums[i]。即0 - i 内存放的数字一定是不含val。

public static int removeElement(int[] nums, int val) {
        
        int length = nums.length;
        int i = 0;
        int j = 0;

        while(j < length){
            if(nums[j] != val){
                nums[i++] = nums[j];
            }
            j++;
        }

        return i;
    }

你可能感兴趣的:(#双指针)