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;
        }
    };
  • 相关阅读:
    PHP Socket服务器搭建和测试
    Linux socket编程示例
    深入浅出讲解:php的socket通信
    Linux系统下/tmp目录文件重启后自动删除
    斐讯K2路由器刷不死固件+openwrt
    php ddos 安全处理代码
    windows通过ftp下载linux文件
    win7 重启dns
    hostname -f 失败解决办法
    ERROR 2003 (HY000): Can't connect to MySQL server on "" (113)
  • 原文地址:https://www.cnblogs.com/csudanli/p/5881987.html
Copyright © 2011-2022 走看看