leetcode 80 Remove Duplicates from Sorted Array II
Remove Duplicates from Sorted Array II:题目链接
解法1:双指针之快慢指针
[0,slow]
存放answer(第二个数组),快指针从索引为1的地方开始遍历,初始时count = 1,已经将数组第一个元素0,计算在[0,slow]这个区间
当快指针与慢指针指向相同元素时:
slow往后移,并将fast指向的内容赋给slow,即nums[++slow] = nums[fast]
,此时count++,执行此过程的前提是count<2
,如果count>=2, 代表[0,slow]中已经有两个该元素了,fast往后移,slow不变
当快指针与慢指针指向不相同元素时:
slow往后移,并将fast指向的内容赋给slow,即
nums[++slow] = nums[fast]
,并将count置为1,表示[0,slow]中有1个该元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import java.util.Arrays;
public class Solution1 { public static int removeDuplicates(int[] nums) { if (nums == null || nums.length == 0) { return 0; }
int slow = 0; // [0,slow] 存放answer int count = 1; for (int fast = 1; fast < nums.length; ++fast) { if (nums[slow] == nums[fast]) { if (count < 2) { nums[++slow] = nums[fast]; count++; } } else { nums[++slow] = nums[fast]; count = 1; } } return slow + 1; }
public static void main(String[] args) { int[] nums = {0, 0, 1, 1, 1, 1, 2, 3, 3}; System.out.println(removeDuplicates(nums)); System.out.println(Arrays.toString(nums)); } }
|
pS:
源代码链接