[Leetcode] Remove Duplicates from Sorted Array

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Remove Duplicates from Sorted Array相关的知识,希望对你有一定的参考价值。

Remove Duplicates from Sorted Array 题解

题目来源:https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/


Description

Given a sorted array, remove the duplicates in-place such that each element appear only once 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


Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the new length.

Solution


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()) return 0;
        int t = nums[0];
        auto it = nums.begin();
        while (it != nums.end()) {
            for (it = nums.begin(); it != nums.end(); ++it) {
                if (it > nums.begin() && (*it) == t) {
                    nums.erase(it);
                    break;
                }
                t = *it;
            }
        }
        return nums.size();
    }
};

解题描述

这道题题意是对给出的一个排好序的数据,删掉其中重复的元素,并且要求空间复杂度为O(1)。上面给出的是我一开始用的比较暴力的办法,使用迭代器来删除vector中元素的办法。

下面给出的是评论区的方法,只需要多使用一个id作为非重复元素标志位即可:


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

以上是关于[Leetcode] Remove Duplicates from Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Remove Element

Leetcode.27 | Remove Element(Python)

LeetCode 546. Remove Boxes

leetcode 27 Remove Element

[Leetcode] 27 Remove Element

LeetCode OJ 27. Remove Element