1. 程式人生 > >[Leetcode] Remove Duplicates from Sorted Array

[Leetcode] Remove Duplicates from Sorted Array

cnblogs not lac xtra href 只需要 一個 function logs

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