LeetCode 80

来源:互联网 发布:注射水银 知乎 编辑:程序博客网 时间:2024/05/22 00:06

原题:

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 1122 and 3. It doesn't matter what you leave beyond the new length.



题意:删除数组中的重复数字,要求同一个数字有两次重复,并返回长度




代码和思路

class Solution {    public int removeDuplicates(int[] nums) {        int i = 0;        for(int n:nums){            //只有在i小于2(小于两个数) 和 后面的数n大于前面第二个数(因为两数重复)时(因为数组是123递增),才进1,否则i指针不动,判断下一个数。            if(i<2 || n > nums[i-2]){                nums[i++] = n;            }                    }        return i;    }}
同理如果是要求只能有一个数重复的,那么就 i<1 || n>[i-1]即可  



原创粉丝点击