zoukankan      html  css  js  c++  java
  • Q5: 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].

    解决原理:

    (若输入数组无序,则先对数组进行排序,则相同值相邻)

    两个游标len,i

    0~len是元素不重复的子数组,即len是目标子数组的最后一个元素的索引

    游标i遍历数组

    若A[i]!=A[len],则为目标子数组增添一个元素

    代码:

     1 class Solution {
     2 public:
     3     int removeDuplicates(int A[], int n) {
     4         int len = 0;
     5         if(n == 0) return 0;
     6         //sort(A,A+n);
     7         for(int i = 1; i < n; i++){
     8             if(A[i] != A[len]){
     9                 len++;
    10                 A[len] = A[i];
    11             }
    12         }
    13         return len+1;
    14     }
    15 };
  • 相关阅读:
    架构师图谱
    P3398 仓鼠找sugar
    NOIP 2017小凯的疑惑
    P2568 GCD
    自动AC机
    qbxt国庆刷题班 游记&总结
    【学习笔记】manacher算法
    [ZROI]分组
    BSGS与扩展BSGS
    Crt and ExCrt
  • 原文地址:https://www.cnblogs.com/ISeeIC/p/4356125.html
Copyright © 2011-2022 走看看