https://leetcode-cn.com/problems/remove-element/
class Solution {
public int removeElement(int[] nums, int val) {
// 快慢指针
int fastIndex = 0;
int slowIndex;
for (slowIndex = 0; fastIndex < nums.length; fastIndex++) {
if (nums[fastIndex] != val) {
nums[slowIndex] = nums[fastIndex];
slowIndex++;
}
}
return slowIndex;
}
}
简单理解就是慢指针一直记录着,允许返回的元素,一旦遇到删除的元素,慢指针停止,快指针去找有没有可以替换它的。
思路来自https://programmercarl.com/0027.移除元素.html#_27-移除元素
还有一道类似的题目:
https://leetcode-cn.com/problems/move-zeroes/
第一次提交:
class Solution {
public void moveZeroes(int[] nums) {
int slow = 0;
int fast = 0;
for (; fast < nums.length; fast++) {
if (nums[fast] != 0) {
nums[slow] = nums[fast];
slow++;
}
}
//把后面的数都变成0
for (; slow < nums.length; slow++) {
nums[slow] = 0;
}
}
}
按照评论区思路改一下做法
class Solution {
public void moveZeroes(int[] nums) {
int slow = 0;
int fast = 0;
for (; fast < nums.length; fast++) {
if (nums[fast] != 0) {
if (fast != slow) {
nums[slow] = nums[fast];
nums[fast] = 0;
}
slow++;
}
}
}
}