[牛客网-Leetcode] #数组 中等 remove-duplicates-from-sorted-array-ii

移除重复数字ii remove-duplicates-from-sorted-array-ii

题目描述

继续思考题目"Remove Duplicates":
给定一个已排序的数组,去除重复元素
如果数组中元素最多允许重复两次呢?
例如:
给出有序数组 A =[1,1,1,2,2,3],
你给出的函数应该返回length =5, A 变为[1,1,2,2,3].

Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array A =[1,1,1,2,2,3],

Your function should return length =5, and A is now[1,1,2,2,3].

解题思路

  • 用快慢两个指针分别记录无重复区域和遍历数组
  • 指针cnt用于记录无重复区域的右下标,初始为0,代表有一个元素
  • 指针index用于遍历元素,初始为1,从第二个元素开始遍历。
  • maxnum用于表示元素的重复次数,初始为1,代表元素仅出现1次
    • 如果A[cnt] == A[index],则maxnum++,进一步判断:
      • 如果maxnum<=2,则A[++cnt] = A[index],index++
      • 如果maxnum>2,则跳过,index++
    • 如果A[cnt] != A[index],则A[++cnt] = A[index],index++,且由于元素不同了,所以maxnum要初始化为1,表示重新记录下一个元素的重复次数
class Solution {
    
    
public:
    int removeDuplicates(int A[], int n) {
    
    
        if(n <= 1) return n;
        int cnt(0), maxnum(1);
        for(int index = 1; index < n; index ++) {
    
    
            if(A[cnt] == A[index]) {
    
    
                maxnum ++;
                if(maxnum <= 2) {
    
    
                    A[++ cnt] = A[index];
                }
            } else {
    
      //A[cnt] != A[index]
                maxnum = 1;
                A[++ cnt] = A[index];
            }
        }
        return cnt + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/106659903