代码实现:
方法一:快慢指针
int removeElement(int *nums, int numsSize, int val) { int slow = 0; for (int fast = 0; fast < numsSize; fast++) { if (val != nums[fast]) { nums[slow++] = nums[fast]; } } return slow; }
方法二:遍历
int removeElement(int *nums, int numsSize, int val) { for (int i = 0; i < numsSize; i++) { if (nums[i] == val) { for (int j = i; j < numsSize - 1; j++) { nums[j] = nums[j + 1]; } numsSize--; i--; } } return numsSize; }