27. 移除元素
看视频不如自己练一练啊,看完总是忘,熟悉一下怎么写
用while循环写一下
int removeElement(int* nums, int numsSize, int val){
int left = 0;
int right = 0;
while(right < numsSize){
if(nums[right] != val){
nums[left] = nums[right];
left++;
right++;
}
else{
right++;
}
}
return left;
}
用for循环写一下
int removeElement(int* nums, int numsSize, int val){
int left = 0;
int right = 0;
for(right;right<numsSize; right++){
if(nums[right] != val){
nums[left] = nums[right];
left++;
}
}
return left;
}
用python写一下
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
left = 0
for right in range(len(nums)):
if nums[right] != val:
nums[left] = nums[right]
left += 1
return left