码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Remove Duplicates from Sorted Array

时间:2018-01-28 14:42:27      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:source   element   tor   删除   str   pos   int   rem   oca   

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

标签:source   element   tor   删除   str   pos   int   rem   oca   

原文地址:https://www.cnblogs.com/yanhewu/p/8370992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!