LeetCode 26 - 删除有序数组的重复元素(简单)

题目链接https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/题目:

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.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

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:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).


Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).


思路:

注意不能使用非常数的额外空间,所以不能定义数组!算法只有一个变量:记录目前重复的元素个数moveforward:每遇到一个和上一个元素相同的元素的时候,这个数量加一,然后将这个元素前置到它之前moveforward的位置上(当然如果和前一个元素不相同的话也会移动到前面,只不过moveforward不会增加罢了)。由于moveforward恒小于i,因此不会对之前的数据有影响。这个可以很容易理解。


代码:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int moveforward;
        int same=0;
        int len=nums.size();
        for(int i=0;i<len;i++){
            if(i==0) moveforward=0;
            else if(nums[i]==nums[i-1]) moveforward++;
            nums[i-moveforward]=nums[i];
        }
        return len-moveforward;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值