题目:给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
class Solution {
public int removeElement(int[] nums, int val) {
if(nums.length==0 || (nums.length == 1 && nums[0] == val)){
return 0;
}
if(nums.length == 1 ){
return 1;
}
int tempLeft = 0;
int tempRight = nums.length - 1;
while(tempLeft < tempRight ){
while(tempRight >= 0 && nums[tempRight] == val ){
tempRight--;
}
if(tempRight < 0 ){
return 0 ;
}
if(nums[tempLeft] == val && tempLeft < tempRight){
nums[tempLeft] = nums[tempRight];
nums[tempRight] = val;
tempRight--;
}
tempLeft++;
}
if(tempRight == tempLeft && nums[tempLeft] == val){
return tempRight;
}else if(nums[tempLeft] == val){
return tempRight+1;
}else{
return tempLeft+1;
}
}
}