7、从数组中删除重复项-II
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].
分析:这一题是从数组中删除重复项-I
https://blog.csdn.net/weixin_43277507/article/details/88092307
的拓展,通过对比题设要求,可以发现,其实只要改变移位位数。我们仍然可以不适用额外的数组空间完成本题。代码如下:
public class Solution {
public static void main(String[] args) {
Solution lt = new Solution();
int []num = {1,1,1,1,2,2,2,3};
int len=lt.removeDuplicates(num);
System.out.println(len);
for(int i=0;i<len;i++)
{
System.out.print(num[i]);
}
}
public int removeDuplicates(int[] nums) {
int len=nums.length;
if (len < 3)
{
return len;
}
int pos = 2;
for (int i=2; i < len ; i++)
{
if(nums[i]!=nums[pos-2])
{
nums[pos++]=nums[i];
}
}
return pos;
}
}