美文网首页
删除排序数组中的重复项 II

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

作者: 叫我颜先生 | 来源:发表于2022-02-28 20:05 被阅读0次
    /*
     * @Author: sumBorn
     * @Date: 2022-02-22 15:02:39
     * @LastEditTime: 2022-02-23 15:05:24
     * @Description: https://leetcode-cn.com/leetbook/read/all-about-array/x9nivs/
     */
    
    /**
     * @description: left,right双指针正常走,统计相同个数,index作为第三个指针进行数组修改
     * @param {*}
     * @return {*}
     */
    public class Solution
    {
        public int RemoveDuplicates(int[] nums)
        {
            int arrLength = nums.Length;
            if (arrLength <= 1) return arrLength;
    
            int index = 0;
            int left = 0;
            for (var right = 1; right < arrLength; right++)
            {
                bool isLast = right == arrLength - 1;
                if (nums[right] != nums[left] || isLast)
                {
                    int offset = right - left;
                    left += offset;
    
                    if (offset == 1)
                    {
                        index++;
                        nums[index] = nums[left];
                    }
                    else if (offset > 1)
                    {
                        nums[index + 1] = nums[index];
                        index += 2;
                        nums[index] = nums[left];
    
                        if (isLast && nums[index] == nums[index - 1]) index--;
                    }
                }
            }
            return ++index;
        }
    }
    
    /**
     * @description: 双指针,和简单删除重复项相似,增加了一个前一位判断
     * @param {*}
     * @return {*}
     */
    public class Solution
    {
        public int RemoveDuplicates(int[] nums)
        {
            int arrLength = nums.Length;
            if (arrLength <= 2) return arrLength;
    
            int left = 1;
            for (var right = 2; right < arrLength; right++)
            {
                if (nums[right] != nums[left] || nums[right] != nums[left - 1])
                {
                    left++;
                    nums[left] = nums[right];
                }
            }
            return ++left;
        }
    }
    
    /**
     * @description: 快慢指针,快指针与慢指针的前两位进行比较,慢指针记录需要替换的位置
     * @param {*}
     * @return {*}
     */
    public class Solution
    {
        public int RemoveDuplicates(int[] nums)
        {
            int arrLength = nums.Length;
            if (arrLength <= 2) return arrLength;
    
            int slow = 2;
            for (var fast = 2; fast < nums.Length; fast++)
            {
                if (nums[fast] != nums[slow - 2])
                {
                    nums[slow] = nums[fast];
                    slow++;
                }
            }
            return slow;
        }
    }
    

    相关文章

      网友评论

          本文标题:删除排序数组中的重复项 II

          本文链接:https://www.haomeiwen.com/subject/wkvolrtx.html