思路:定义一个指针left,使该指针及该指针左边的数全部都不等于val,定义一个遍历指针i,若nums[i] == val,则i自加,若nums[i] != val,则将left++,并将nums[i]的值赋给nums[left],i++;最后返回left + 1即可
以示例2举例:初始left = -1,i = 0;val = 2
0,1,2,2,3,0,4,2 left = -1,i = 0,nums[i] != val -> left++;nums[left] = nums[i]; i++
0,1,2,2,3,0,4,2 left = 0,i = 1,nums[i] != val -> left++;nums[left] = nums[i]; i++
0,1,2,2,3,0,4,2 left = 2,i = 2 nums[i] == val -> i++
0,1,2,2,3,0,4,2 left = 2,i = 3 nums[i] == val -> i++
0,1,2,2,3,0,4,2 left = 2,i = 4 nums[i] != val -> left++;nums[left] = nums[i]; i++
0,1,2,2,3,0,4,2 left = 3,i = 4 nums[i] != val -> left++;nums[left] = nums[i]; i++
0,1,2,2,3,0,4,2 left = 3,i = 5 nums[i] != val -> left++;nums[left] = nums[i]; i++
0,1,2,2,3,0,4,2 left = 3,i = 6 nums[i] != val -> left++;nums[left] = nums[i]; i++
0,1,2,2,3,0,4,2 left = 3,i =7 nums[i] == val -> i++
Java实现:
class Solution {public int removeElement(int[] nums, int val) {int left = -1;for(int i = 0;i < nums.length;i++){if(nums[i] != val){left++;nums[left] = nums[i];}}return left + 1;}
}