zoukankan      html  css  js  c++  java
  • LeetCode 80. Remove Duplicates from Sorted Array II

    Follow up for "Remove Duplicates":
    What if duplicates are allowed at most twice?

    For example,
    Given sorted array nums = [1,1,1,2,2,3],

    Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.


     

    题目要求去除重复的元素,每个元素最多重复2次,是比较典型的的双指针问题,第一个指针记录无重元素序列的末尾,第二个元素负责遍历整个数组。有一个问题需要注意一下,这里最多只允许重复两次,所以需要再设置一个变量count来表示重复了几次,count初始值为1,如果有元素重复则该值减一;如果没有重复则恢复为1,由于该数组为有序数组,元素递增,当前数字不重复则以后也不会有该数字的重复。
     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         int len = nums.size();
     5         if (len <= 2)
     6             return len;
     7         int pre = 0, cur = 1, count = 1; // pre和cur分别表示快慢指针,count用来表示是否已经到达重复次数的限制  0表示已经重复到2次,1表示没有
     8         while (cur < len)
     9         {
    10             if (nums[cur] == nums[pre] && count == 0)
    11                 cur++;
    12             else
    13             {
    14                 if (nums[cur] == nums[pre])
    15                     count--;
    16                 else
    17                     count = 1;
    18                 nums[++pre] = nums[cur++];
    19             }
    20         }
    21         return pre + 1;
    22         
    23     }
    24 };

    当然也可以写的更简洁一些,但是不太好理解,不过思路是类似的,因为是有序数组,可以通过比较大小来判断数字是否重复

     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         int i = 0;
     5         for (auto n : nums) {
     6             if (i <= 1 || n > nums[i-2])  {
     7                 nums[i++] = n;
     8             }
     9         }
    10         return i;    
    11     }
    12 };
     
     
  • 相关阅读:
    Linux 文件特殊权限 SUID SGID SBIT
    Oracle Flashback 详解
    Oracle RMAN备份与还原注意事项
    Linux df 与du用法
    Oracle RMAN备份与还原
    Oracle 不小心删除undo数据文件以及磁盘空间不足导致不能登录的解决办法
    Oracle 内存参数调优设置
    Oracle Profile 配置文件
    关于php语言的使用!
    分享几个Javascript 封装方法
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8387796.html
Copyright © 2011-2022 走看看