leetCode 80.Remove Duplicates from Sorted Array II (删除排序

Follow up for "Remove Duplicates":What if duplicates are allowed at mosttwice?

For example,Given sorted arraynums=[1,1,1,2,2,3],

Your function should return length =5, with the first five elements ofnumsbeing1,1,2,2and3. It doesn’t matter what you leave beyond the new length.

思路:本题允许数组最多有两个重复,,所以需要加一个判断,是否到两个。具体代码如下:

public class Solution {public int removeDuplicates(int[] nums) {if(nums.length <= 2){//长度小于2,直接返回return nums.length;}boolean isTwice = false;//是否两次int len = 0;//最新长度for(int i = 0; i < nums.length; i++){//遍历//不等于最后一个切数字相等if(i != nums.length -1 && nums[i+1] == nums[i]){if(!isTwice){//还没两次isTwice = true;nums[len++] = nums[i]; //添加到数组最前}}else{//不相等isTwice = false;//标记为不是两次nums[len++] = nums[i];//添加最前}}return len;}}

版权声明:本文为博主原创文章,未经博主允许不得转载。

用敬业的精神去面对每一份挑战,

leetCode 80.Remove Duplicates from Sorted Array II (删除排序

相关文章:

你感兴趣的文章:

标签云: