原题:

https://leetcode.cn/problems/remove-element/description/?envType=study-plan-v2&envId=top-interview-150

题解:

public int removeElement(int[] nums, int val) {
    int tail = nums.length-1;
    int head = 0;
    while (tail >= head) {
        if (nums[head] != val) {
            head++;
            continue;
        }
        if (nums[tail] == val) {
            tail--;
            continue;
        }
        //赋值
        nums[head++] = nums[tail--];
    }
    return head;
}

解析:

  1. 不等于val的值前移,相等的放在后面,那么最后面一定是无效元素,采用双指针的方式,依次来交换前后位置。即,头指针找无效数据,尾指针找有效数据,都找到后交换,然后继续下一步。