p80

LeetCode 80 Remove Duplicates from Sorted Array II 题解

1.题目:

Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.
Subscribe to see which companies asked this question

题意:

输入一个有序数组,去除数组中重复的元素,(允许两个重复的存在),并输出最后的元素的个数。

2.解题思路:

标记一个flag,注意边界条件

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 

public class Solution {
public int removeDuplicates(int[] nums) {
int ans=1;
int flag=1;
if (nums.length<3)
{
return nums.length;
}
for (int i=1;i<nums.length;i++)
{
if (nums[i]==nums[i-1])
{
flag++;
if (flag<3)
{
nums[ans]=nums[i];
ans++;
}


}
else {
nums[ans]=nums[i];
ans++;
flag=1;
}

}
return ans;
}
}


4.一些总结: