leetcode 80. Remove Duplicates from Sorted Array II

来源:互联网 发布:java马士兵视频尚学堂 编辑:程序博客网 时间:2024/06/05 19:46

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.

public int removeDuplicates(int[] nums) {        int value = Integer.MIN_VALUE;        int count = 0;        int index = 0;        for(int i = 0; i < nums.length;i++){            if(nums[i] != value){                value = nums[i];                count = 1;                nums[index++] = nums[i];            }            else{                if(count == 1){                    nums[index++] = nums[i];                    count++;                }                else{                    count ++;                }            }        }        return index;    }

就地修改一个有序数组 每个数字保留两个
比如 :
1 1 1 1 2 2 2 2 3 3
逻辑上应该返回1 1 2 2 3 3
但是因为是就地修改 不是新建一个数字存储结果
所以实际上是 :
这里写图片描述
上面是逻辑的图
其实是在同一个数组里修改 会覆盖的
也就是一个指针遍历箭头的始点
另一个指针遍历箭头的终点
始点如果看到当前值已经有两个了 就不画箭头 最终始点到头 了
数组变成了1122332233 后面4个没有被覆盖
函数返回6 这样就可以在原数组截取前6位得到结果

0 0
原创粉丝点击