力扣0080——删除有序数组中的重复项II

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

难度:中等

题目描述

给你一个有序数组 nums ,请你原地删除重复出现的元素,使得出现次数超过两次的元素只出现两次 ,返回删除后数组的新长度。
不要使用额外的数组空间,你必须在 原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

说明
为什么返回数值是整数,但输出的答案是数组呢?
请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
你可以想象内部操作如下:

// nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

示例1

输入:nums = [1,1,1,2,2,3]
输出:5, nums = [1,1,2,2,3]

示例2

输入:nums = [0,0,1,1,1,1,2,3,3]
输出:7, nums = [0,0,1,1,2,3,3]

题解

如果数组长度小于等于2,直接返回数组的长度
如果长度大于2,执行如下操作

  • i n d e x = 1 index=1 index=1
  • 从第三个数开始循环,如果 n u m s [ i ] = n u m s [ i n d e x ] nums[i] = nums[index] nums[i]=nums[index] && n u m s [ i n d e x ] = n u m s [ i n d e x − 1 ] nums[index] = nums[index-1] nums[index]=nums[index1],跳过本次循环
  • 将当前下标的元素值赋值到index的位置,并让index自增

想法代码

class Solution
{
    public static void Main(String[] args)
    {
        int[] nums = { 1, 1, 1, 2, 2, 3 };
        Solution solution = new Solution();
        int len = solution.RemoveDuplicates(nums);
        Console.WriteLine(len);
        for (int i = 0; i < len; i++)
        {
            Console.Write(nums[i] + " ");
        }
    }

    public int RemoveDuplicates(int[] nums)
    {
        if (nums.Length <= 2)
        {
            return nums.Length;
        }
        int index = 1;
        for (int i = 2; i < nums.Length; i++)
        {
            if (nums[i] == nums[index] && nums[index] == nums[index - 1])
            {
                continue;
            }

            nums[++index] = nums[i];
        }
        return index + 1;
    }
}

你可能感兴趣的:(leetcode,算法)