• 删除排序数组中的重复项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;
        }
    }
  • 相关阅读:
    Ubuntu14.04升级cmake版本的方法
    在ubuntu16.04-32bits 下编译vlc和vlc-qt开源项目
    从Ubuntu 14.04 LTS版升级到Ubuntu 16.04 LTS
    如何使用Heartbeat,组建一个高可用性的mysql集群
    VLC和Qt结合编写流媒体rtsp播放器
    How to Analyze "Deadlocked Schedulers" Dumps?---WINDBG
    sqlserver-kit.org
    SQLSERVER ----improvedk
    sql server博客
    分享]国外最新安全推文整理
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/11623756.html
Copyright © 2020-2023  润新知