• Leetcode OJ: Remove Duplicates from Sorted Array I/II


    删除排序数组重复元素,先来个简单的。

    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].

    简单粗暴,重复一个则偏移量加1,遍历一次令A[i-k]=A[i]就可以了。看代码:

     1 class Solution {
     2 public:
     3     int removeDuplicates(int A[], int n) {
     4         if (n <= 1)
     5             return n;
     6         int k = 0;
     7         for (int i = 1; i < n; ++i) {
     8             if (A[i] == A[i - 1]) {
     9                 ++k;
    10             } else if (k > 0) {
    11                 A[i-k] = A[i];
    12             }
    13         }
    14         return n - k;
    15     }
    16 };

    题目加些条件:

    Follow up for "Remove Duplicates":
    What if duplicates are allowed at most twice?

    For example,
    Given sorted array A = [1,1,1,2,2,3],

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

    允许重复出现两次。

    LZ比较实在,只是老实的把以上代码的A[i]==A[i-1]的条件变成了i > 1 && A[i] ==  A[i-1] && A[i] == A[i-2]

    然后果断受教育

    Input:[1,1,1,2,2,3]

    Output:[1,1,2,3]

    Expected:[1,1,2,2,3]

    分析原因:A[i-2]有可能不是原来的值了,因为是连续判断3个值,偏移只是偏移1个值,步长不对称。
    天真地以为只有这个坑,于是加了个对k的约束,判断条件变成k != 1 && A[i] == A[i - 1] && A[i] == A[i - 2]
    果断再次受教育
    Input:[1,1,1,1]

    Output:[1,1,1]

    Expected:[1,1]

    该偏移时不偏移了。
    好吧,还是好好整理思路吧。
    这里加的条件是允许2个,那如果条件逐渐变成允许3个、4个呢?
    连写几个比较很明显是不行的,而且还要考虑各种情况,很复杂,设计一个通用的方案更靠谱。
    LZ想到的是计数的方法了,记录上一次重复的次数,然后判断次数是否允许,允许则进行偏移,不允许则偏移量加1。
    且看代码:
     1 class Solution {
     2 public:
     3     int removeDuplicates(int A[], int n) {
     4         int k = 0;
     5         int count = 1;
     6         for (int i = 1; i < n; ++i) {
     7             if (A[i] == A[i - 1]) {
     8                 count++;
     9                 if (count > 2) {
    10                     k++;
    11                     continue;
    12                 }
    13             } else {
    14                 count = 1;
    15             }
    16             if (k > 0) 
    17                 A[i - k] = A[i];
    18         }
    19         return n - k;
    20     }
    21 };
  • 相关阅读:
    Redis主从复制
    Centos6克隆虚拟机改IP和mac地址
    Liunx中ERROR 2002 (HY000) Can't connect to local MySQL server through socket 'varlibmysqlmysql.sock' (2)报错
    linux安装redis
    每天五分钟带你了解Redis
    sqiud --ACL控制应用、sarg日志分析、反向代理
    squid--透明代理
    Squid--传统代理
    Tomcat+Nginx实现动静分离
    -bash: nginx: 未找到命令/没有这个文件
  • 原文地址:https://www.cnblogs.com/flowerkzj/p/3619490.html
Copyright © 2020-2023  润新知