标签:
https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
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]
.
解题思路:
与Remove Duplicates from Sorted Array相比,这道题稍微复杂点。因为要求一个数字最多可以出现两次,很容易想到在上题的基础上,加入一个变量计数。i作为遍历游标,遇到比record大的数字时,操作不变,同时将count重置为1。区别就是,遇到和record相等的数字,原来是不需要操作的,这里首先count必须++。其次,如果在++前,count<2,那么还需要把当前数字和swapIndex的数字交换位置,同时swapIndex++。这种情况下的swap开始忘记了,导致程序一直出错。
同样,不swap,直接A[swapIndex] = A[i],也是可以的。
public class Solution { public int removeDuplicates(int[] A) { if(A.length == 0){ return 0; } int swapIndex = 1; int count = 1; int record = A[0]; for(int i = 1; i < A.length; i++){ if(A[i] == record){ if(count < 2){ int temp = A[swapIndex]; A[swapIndex] = A[i]; A[i] = temp; swapIndex++; } count++; } if(A[i] > record){ record = A[i]; // if(count > 2){ int temp = A[swapIndex]; A[swapIndex] = A[i]; A[i] = temp; // } swapIndex++; count = 1; } } return swapIndex; } }
Remove Duplicates from Sorted Array II
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4273119.html