LC80.删除有序数组中的重复项II

原题链接
image.png

思路:

  • 标准的store_index类型模板题。本质上是`数组中相邻重复元素允许保留n个问题。
  • 相当于加强版的unique函数。
  • 起始的store_index指向数组的开头位置,遍历指针i也指向数组的开头位置,如果当前位置的数字符合条件,那么就将其放入store_index位置当中,同时store_index += 1
  • 如何判定“当前位置的数字符合条件”?如果nums[i] == nums[store_index - 1] == nums[store_index - 2],那么就不符合条件,反之则符合条件。

    代码

    1. class Solution {
    2. public:
    3. int removeDuplicates(vector<int>& nums) {
    4. int store_index = 0, n = nums.size();
    5. for (int i = 0; i < n; ++i) {
    6. if (i <= 1) {
    7. store_index += 1;
    8. } else {
    9. if (nums[i] != nums[store_index - 1] || nums[i] != nums[store_index - 2]) {
    10. nums[store_index] = nums[i];
    11. store_index += 1;
    12. }
    13. }
    14. }
    15. return store_index;
    16. }
    17. };