双指针删除数字重复项
class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 0){ return 0; } int slow = 0, fast = 0; while(fast < nums.length){ if(nums[fast] != nums[slow]){ slow++; nums[slow] = nums[fast]; } fast++; } //长度都是索引+1 return slow + 1; } }
class Solution { public void moveZeroes(int[] nums) { int p = removeElement(nums, 0); for(int i = p; i < nums.length; i++){ nums[i] = 0; } } //双指针移动元素 返回移出目标元素后的数组末尾下标 public int removeElement(int[] nums, int target){ int fast = 0, slow = 0; while(fast < nums.length){ if(nums[fast] != target){ nums[slow] = nums[fast]; slow++; } fast++; } return slow; } }