Remove Duplicates from Sorted Array II
来源:互联网 发布:linux网络编程开源项目 编辑:程序博客网 时间:2024/04/30 06:23
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]
这一篇跟前一篇多了一个条件,就是允许两个重复的存在。
中间存在一个小小的坑,自己没考虑到,就是如果相等且之前未重复过的话,那么也是需要移位的。
比如[1,1,1,1,3,3]。A[4]一开始移到A[2]位置上,这个时候A[5]也是需要移到A[3]的。
上代码:
public class Remove_Duplicates_from_Sorted_Array_II {public class Solution {public int removeDuplicates(int[] A) {int lengthA = A.length;if (lengthA == 0)return 0;int now = A[0];int start = 0;boolean same = false;for (int indexA = 1; indexA < A.length; ++indexA) {if (now == A[indexA] && same) {// 相等且重复过。lengthA -= 1;// same=false;// start=indexA;} else {if (now == A[indexA]) {// 相等且未重复过same = true;A[start + 1] = A[indexA];// 相等且未重复过的话,有时候也是需要移动的!start++;} else if (start != indexA + 1) {// 不相等A[start + 1] = A[indexA];now = A[indexA];start++;// 空闲位置右移same = false;}// start = indexA;}}return lengthA;}}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub}}
0 0
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove duplicates from sorted array II
- Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- SEO之不能说的秘密
- Linq to XML 增删改查
- CSS魔法堂:盒子模型简介
- Linux系统Loadaverage负载详细解释
- Symfony - view
- Remove Duplicates from Sorted Array II
- 原创内容的五个技巧
- DockerFile详解
- cocos2d-x 3.2 椭圆运动
- 某通信设备集团公司日常巡检应用案例
- 如何做好百度引擎排名
- [.Net码农]收集一些字符串的用法
- 平衡树的调整 案例与代码
- JQuery语法