zoukankan      html  css  js  c++  java
  • [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;
        }
    };
    
    
  • 相关阅读:
    集训队日常训练20180518-DIV1
    集训队日常训练20180513-DIV1
    python类的使用与多文件组织
    性能指标
    python调用.so
    动态链接库的使用
    python读写xml文件
    使用python读取文本中结构化数据
    python画图
    numpy及scipy的使用
  • 原文地址:https://www.cnblogs.com/yanhewu/p/8370992.html
Copyright © 2011-2022 走看看