zoukankan      html  css  js  c++  java
  • 删除排序数组中的重复项II

    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;
        }
    }
  • 相关阅读:
    JQuery有几种选择器?
    Java有哪些基本数据类型
    您认为做好测试用例设计工作的关键是什么?
    final关键字
    目前主要的测试用例设计方法是什么?
    举例说明同步和异步。
    maven配置多个镜像
    参数Parameters、变量Variables
    jsp文件导包
    动态横切
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/11623756.html
Copyright © 2011-2022 走看看