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 A = [1,1,2],

    Your function should return length = 2, and A is now [1,2].

    发现一道遗留的easy题,说来惭愧,看见这题第一眼就觉得尼玛这不和remove element 一模一样吗,只是这回是要移除重复的,而且对内存有了O(1)的严格限制。同样要求是 in-place 的操作数组,可是我居然忘了当时remove element是怎么做的了。。。相当时我还写出三种解法的啊,怎么现在都想不起来了=_=

    仔细回顾了一下之前的博客,终于回想起来了。时间复杂度为O(n) 空间为O(1) 。大体思路就是追踪当前已经删除元素的数量,然后把后面的元素往前移动。

    int removeDuplicates(int A[], int n) {
        if (n <= 0 ) return 0;
        int curdel = 0;
        int prev = A[0];
        int len = n;
        for (int i = 1; i < n; i++) {
            int cur = A[i];
            if (cur == prev) {
                len--;
                curdel++;
            }else {
                if (curdel > 0) {
                    A[i-curdel] = A[i];
                }
            }
            prev = cur;
        }
        return len;
    }
  • 相关阅读:
    Js图片利用定时器自动切换(setInterval)
    JS全选,全不选,添加,删除功能的实现
    windows 下安装memcache拓展
    Linux 踢出其他用户
    通过nginx配置php环境变量
    Mac 服务重启
    Mac PHP安装redis扩展
    高并发解决方案
    MySQL 分表
    MySQL 主从-简介
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4156662.html
Copyright © 2011-2022 走看看