问题:
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,2,3],
Your function should return length = 5,with the first five elements of nums being 1,2 and 3. It doesn’t matter what you leave beyond the new length.
这个问题相对而言比较简单,在纸上画1下处理进程便可。
代码示例:
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length < 1) {
return 0;
}
int begin = 0;
int end = 1;
//记录同1个字符重复的次数
int count = 1;
while (end < nums.length) {
//end与begin对应数1致时
if (nums[end] == nums[begin]) {
//更新count
++count;
//count <= 2时,将end移动到begin后1个位置,同时增加begin
//否则,数量过量,不移动begin,直到找到下1个不1样的数
if (count <= 2) {
nums[begin+1] = nums[end];
++begin;
}
} else {
//找到不1样的数,将end移动到begin后1个位置,同时增加begin
count = 1;
nums[begin+1] = nums[end];
++begin;
}
++end;
}
return begin+1;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。