zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    用Zend Studio12 导入在workspace中的项目
    PHP 统计中文字符串的长度
    jQuery判断checkbox是否选中的3种方法
    js,jquery获取下拉框选中的option
    HTML与XHTML的区别
    HTML头部
    HTML框架标签
    js的继承
    图片懒加载
    Http请求的gzip压缩
  • 原文地址:https://www.cnblogs.com/csudanli/p/5881987.html
Copyright © 2011-2022 走看看