zoukankan      html  css  js  c++  java
  • Leetcode题目:Remove Duplicates from Sorted Array

    题目: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 in place with constant memory.

    For example,
    Given input array 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.

    题目解答:

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int size = nums.size();
            if(size <= 1)
                return size;
            int cur_index = 0;
            int next = 1;
            for(; next < size; next++)
            {
                if(nums[cur_index] == nums[next])
                    continue;
                else
                {
                    cur_index++;
                    nums[cur_index] = nums[next];
                }
            }
            return cur_index + 1;
        }
    };

    题目发散:

    上面的代码是自己在编程的时候直接反应写出来的答案。AC之后,想到了C++的STL中,有一个函数unique也可以实现对有序数组的一个去重。

    unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

    需注意的是:unique返回的是一个迭代器,即出现重复的第一个位置。

    [1 , 1,  2 , 2 , 3 , 4]

    使用unique之后得到的数组,如下

    [1 , 2 , 3 , 4 , 1 , 2]

    对于上面的这个数组,begin指向1,end指向最末的2的后面的一个位置,那么unique返回的迭代器指向下面这个数组的第二个1的位置。

    于是便重新写了下面这个。

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if(nums.size() <= 1)
                return nums.size();
            vector<int>::iterator nums_end_it = unique(nums.begin(),nums.end());
            return nums_end_it - nums.begin();
        }
    };
  • 相关阅读:
    markdown基础使用技巧
    用ps实现提高照片的清晰度
    正则表达式匹配:中、日、韩文
    解决"$ is not defined" 亲自体验
    [NLP] 相对位置编码(一) Relative Position Representatitons (RPR)
    [NLP] cs224n-2019 Assignment 1 Exploring Word Vectors
    [Deep Learning] GELU (Gaussian Error Linerar Units)
    [Python] 等号赋值, copy, deepcopy的区别
    [微积分] 利用极坐标计算二重积分
    [c++] C++多态(虚函数和虚继承)
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5181146.html
Copyright © 2011-2022 走看看