码迷,mamicode.com
首页 > 编程语言 > 详细

删除排序数组中的重复项II

时间:2019-10-05 00:34:49      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:应该   变量   code   return   网络   value   sorted   turned   oca   

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 respectively.

It doesn‘t matter what you leave beyond the returned length.
Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn‘t matter what values are set beyond the returned length.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

创建一个游标temp,初始化为第一个元素,创建一个变量res,记录当前表的长度,创建一个变量count,记录元素的重复次数。

遍历表中元素,如果当前访问到的元素与游标不相等,则此元素要加入新的数组中,因此res+1,并且游标需要更新;如果访问到的元素与游标相等,变量count+1,如果count的次数不大于2,说明此元素应该加入新的数组中,若count>2,不做处理,继续访问下一位元素。代码如下:

class Solution {
    public int removeDuplicates(int[] nums) {
        int length = nums.length;
        if(length <= 2)
        {
            return length;
        }
        int res = 1;
        int temp = nums[0];
        int count = 1;
        for(int i = 1; i < length; i++)
        {
            if(nums[i] != temp)
            {
                nums[res++] = nums[i];
                temp = nums[i];
                count = 1;
            }
            else
            {
                count++;
                if(count <= 2)
                {
                    nums[res++] = nums[i];
                }
            }
        }
        return res;
    }
}

 

删除排序数组中的重复项II

标签:应该   变量   code   return   网络   value   sorted   turned   oca   

原文地址:https://www.cnblogs.com/WakingShaw/p/11623756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!