LeetCode26. 删除有序数组中的重复项

给定一个升序排列的整数数组nums,你需要原地删除重复出现的元素,使得每个元素只出现一次,返回删除后数组的新长度。使用快慢指针的方法,当快指针所指元素与前一个不同,则将该元素替换左指针位置的元素并向前移动左指针。
摘要由CSDN通过智能技术生成

26. 删除有序数组中的重复项 - 力扣(LeetCode)

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements to nums.

Consider the number of unique elements of nums to be k. To get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.

Return k.

给你一个 升序排列 的数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。

考虑 nums 的唯一元素的数量为 k ,你需要做以下事情确保你的题解可以被通过:

更改数组 nums ,使 nums 的前 k 个元素包含唯一元素,并按照它们最初在 nums 中出现的顺序排列。nums 的其余元素与 nums 的大小不重要。返回 k 。

//手撕
class Solution {
    public int removeDuplicates(int[] nums) {
        int length =nums.length;
        if(length==0){
            return 0;
        }
        int left=1;
        int right=1;
        while(right<length){
            if(nums[right]!=nums[right-1]){
                nums[left]=nums[right];
                left++;
            }
            right++;
        }
        return left;
    }
}

 题解:本题在删除元素同时要保持相对位置不变,所以采用快慢指针的方法,在快指针与前一个位置数值不同时则说明移动到了替换位置这时将其替换当前left,需要注意的是在运动过程中快指针容易跳动多个位置,左指针只有在需要变换时才向后移位即移至替换位。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值