• leetcode


    Remove Duplicates from Sorted Array I

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

    Remove Duplicates from Sorted Array II

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

    个人思路:

    1,将整个数组看成两个部分,前半部分是符合题目要求的数组,后半部分是待探索的数组,设置两个用于遍历的变量index和i,index用于定位前半部分数组的末尾,i用于定位后半部分的数组,在两个部分之间的元素是被剔除的元素

    2,同时设置一个变量count用于记录重复次数,再设置一个变量limit用于记录可重复的最大次数,这样一共4种情况,A[index] == A[i]时,count大于limit或者count不大于limit,A[index] != A[i]时,count大于limit或者count不大于limit

    3,通过i的遍历,不断将符合题目要求的元素加入到前半部分数组中

    代码:

     1 class Solution {
     2 public:
     3     int removeDuplicates(int A[], int n) {
     4 
     5         if (n < 2)
     6         {
     7             return n;
     8         }
     9 
    10         const int limit = 2; //I设为1,II设为2
    11         int index = 0, i = 1, count = 1;
    12 
    13         while (i < n)
    14         {
    15             if (A[index] == A[i])
    16             {
    17                 ++count;
    18                 if (count > limit)
    19                 {
    20                     ++i;
    21                 }
    22                 else
    23                 {
    24                     A[++index] = A[i++];
    25                 }
    26             }
    27             else
    28             {
    29                 A[++index] = A[i++];
    30                 count = 1;
    31             }
    32         }
    33 
    34         return index + 1;
    35     }
    36 };
    View Code

    通过这两个题目,可以总结出一个对数组进行处理的一般性方法(要求空间复杂度为常数),即将整个数组看成两个部分,前一部分是符合要求的,需要用一个变量来定位这个部分,后一部分是待处理的,通过一个变量来定位和遍历,这两部分中间可能有剩余元素(这部分是被处理过不合要求的),通过遍历处理后一部分的元素,将不断扩张前一部分的数组,直到后一部分的元素都遍历完,整个处理过程就结束了

  • 相关阅读:
    k8s记录-helm部署(九)
    k8s记录-master组件部署(八)
    Hadoop记录-Apache hadoop+spark集群部署
    k8s记录-ubuntu安装docker
    Nginx记录-Proxy_pass多个应用配置(转载)
    Java动态调用脚本语言Groovy
    05 吸收应用-会整理还不够?教你吸收、联想、输出、应用
    02 超级搜索术——资源搜索:全面、快速查找全网你想要的任何信息、情报
    01 超级搜索术——信息搜索:全面、快速查找全网你想要的任何信息、情报
    长赢指数基金投资计划-201807(一补仓)
  • 原文地址:https://www.cnblogs.com/laihaiteng/p/3984493.html
Copyright © 2020-2023  润新知