【leetcode 数组】Remove Duplicates from Sorted Array II

来源:互联网 发布:工地临时用电计算软件 编辑:程序博客网 时间:2024/04/23 23:29

题目:

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].

Hide Tags
 Array Two Pointers








分析:

与上一篇Remove Duplicates from Sorted Array不同,题目要求允许每个数最多重复两次,则可以设置一个标志位flag用于标记




代码参考:

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n==0)  return 0;        int flag=1;      //标记变量,表示重复的个数        int index=0;        for(int i=1;i<n;i++)        {        if(A[index]==A[i] && flag==1)                   { A[++index]=A[i];  flag=2;}        else if(A[index]!=A[i])          { A[++index]=A[i];  flag=1;}        }        return index+1;    //下标加1  表个数    }};




0 0
原创粉丝点击