Remove Duplicates from Sorted Array II

来源:互联网 发布:搜狗输入法下载 linux 编辑:程序博客网 时间:2024/06/06 11:45

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 相似,只是要加入一个flag让一个数存在两次;

注意第一个,如果相等,还是要把重复的数从右边copy到左边来,因为比如1,1,1,1,3,3 -> 1,1,3,3 这里的一个3必须从后面copy过来,因为这里本来是1,如果不copy就出错了.

public class Solution {     public int removeDuplicates(int[] nums) {         if(nums == null) return -1;         if( nums.length <=1) return nums.length;         int i=0; int j=1;          boolean findonce = false;         while(j<nums.length){             if( nums[i] == nums[j]){                 if(findonce == false){                     findonce = true;                     nums[++i] = nums[j]; //这里需要copy过来;因为中间会有之前的重复,后面发现新的相等number,必须copy到前面来;                }                  j++;             } else { // nums[i] != nums[j];                 findonce = false; //这里需要重置一下;                nums[++i] = nums[j];                 j++;             }         }         return i+1;     } }


0 0