[LeetCode]Remove Duplicates from Sorted Array II
这是我最开始的做法,两个指针,一个count计数,但是思路不是很清晰,代码上也有些冗余
public class Solution { public int removeDuplicates(int[] nums) { int length = nums.length; int p1 = 1; int p2 = 1; int count = 0; while (p2 < length) { if (count == 2) { if (nums[p2] != nums[p1]) { nums[p1] = nums[p2]; count = 0; p1 ++; } p2 ++; } else { nums[p1] = nums[p2]; if (nums[p1] == nums[p1 - 1]) { count ++; } else { count = 0; } if (count < 2) p1 ++; p2 ++; } } return p1; } }
这个思路参考了一下网上 就清晰很多了
public class Solution { public int removeDuplicates(int[] nums) { int index = 0; for (int i = 0; i < nums.length; i++) { int j = i; for (; j < nums.length; j++) { if (nums[i] != nums[j]) { break; } if (j - i < 2) { nums[index++] = nums[i]; } } i = j - 1; } return index; } }