• LeetCode 26. 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.

    Subscribe to see which companies asked this question

    给你一个已经排好序的数组,让你去掉中间重复的元素,注意:不能用额外的空间再建一个数组,你必须在一个固定的内存中,返回值为新的数组长度,只要数组的开头是
    删减后的数组就行,后面的不管
     
    我们第一想到的就是建立一个前驱,如果等于前驱,就把后面的数组元素前移,遍历完全即可,但是这样的时间复杂度为O(n*n),提交后会超出时间限制
     
    再思考,我们就会遇到重复的并不着急前移,统计好这个元素前面有多少重复元素假设为N,直接前移N的单位即可,时间复杂度为O(n)
     
    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if (nums.size() < 2)return nums.size();
            int pre = nums[0];
            int count = 0;
            for (int i = 1;i < nums.size();++i)
            {
                if (nums[i] == pre)
                {
                    ++count;
                }
                else
                {
                    nums[i - count] = nums[i];
                    pre = nums[i];
                }
            }
            return nums.size() - count;
        }
    };
  • 相关阅读:
    读取XML字符串到临时表
    Golang学习笔记
    Golang环境配置Centos
    IntelliJ Idea 常用快捷键列表
    Elasticsearch的Groovy Script自定义评分检索
    MSSQL读取xml字符串到临时表
    通过反射给对象属性动态赋值总结(含可空属性)
    。。。。。
    指定位置输出函数
    DBhelper
  • 原文地址:https://www.cnblogs.com/csudanli/p/5881987.html
Copyright © 2020-2023  润新知