LeetCode Remove Duplicates from Sorted Array II
来源:互联网 发布:stc12c系列单片机 编辑:程序博客网 时间:2024/06/06 08:59
题目大意:给出一个排序后的数组,去除数组中的重复元素且最多允许有两个元素相同,最后返回处理后的数组长度,且数组是整理后的。
算法思想:当数组长度小于3时不用整理数组,直接返回数组的长度;当数组长度大于等于3时,用pre记录前驱元素,flag标记是否重复一次,p记录新数组的末端坐标,然后扫描整个数组,相邻两个元素比较,如果相同且flag=0则将比较的元素放入到新数组中,flag=1,反之,如果量元素相同则continue,若不相同将比较元素放入到新数组中flag=0。
代码如下:
class Solution {public: int removeDuplicates(int A[], int n) { int p;//记录新数组的末端 int pre;//前趋变量 int flag;//标记元素重复几次 if(n==0||n==1||n==2){ return n; } else{ pre=A[0]; flag=0; p=1; for(int i=1;i<n;i++){ if(pre==A[i]&&!flag){ A[p++]=A[i]; flag=1; } else{ if(pre==A[i]) continue; else{ pre=A[i]; A[p++]=A[i]; flag=0; } } } return p; } } };
0 0
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- 【leetcode】Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Leetcode Remove Duplicates from Sorted Array II
- SSL/TLS协议运行机制的概述
- JAVA实现栈
- UVA - 10717 Mint
- [GIT] warning: LF will be replaced by CRLF问题解决方法
- 64位ubuntu kylin配置QT for Android
- LeetCode Remove Duplicates from Sorted Array II
- uva 624 CD (01背包)
- Perl 特殊符号
- 算法导论学习笔记 6.5 优先队列
- HDU 2509 Be the Winner(尼姆博弈)
- acm 频率最高
- 《转载》异常: The Network Adapter could not establish the connection
- IT人士必去的10个网站
- 关于温湿度SHT20传感器,用普通GPIO口来模拟IIC实现驱动