zoukankan      html  css  js  c++  java
  • 26. Remove Duplicates from Sorted Array【easy】

    26. Remove Duplicates from Sorted Array【easy】

    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.

    解法一:

     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         if (nums.empty() || nums.size() == 1)
     5         {
     6             return nums.size();
     7         }
     8         
     9         int i = 0; 
    10         int j = 0;
    11         nums[j++] = nums[i++];
    12         
    13         while (i < nums.size() && j < nums.size())
    14         {
    15             if (nums[i] != nums[i - 1])
    16             {
    17                 nums[j++] = nums[i++];
    18             }
    19             else
    20             {
    21                 ++i;
    22             }
    23         }
    24         
    25         return j;
    26     }
    27 };

    思路:双指针,注意边界条件的判断

    解法二:

     1 class Solution {
     2     public:
     3     int removeDuplicates(int A[], int n) {
     4         if(n < 2) return n;
     5         int id = 1;
     6         for(int i = 1; i < n; ++i) 
     7             if(A[i] != A[i-1]) A[id++] = A[i];
     8         return id;
     9     }
    10 };

    可读性一般

    解法三:

     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         int count = 0;
     5         for(int i = 1; i < nums.size(); i++){
     6             if(nums[i] == nums[i-1]) count++;
     7             else nums[i-count] = nums[i];
     8         }
     9         return nums.size()-count;
    10     }
    11 };
  • 相关阅读:
    Python 中多线程之 _thread
    Python ftplib 模块关于 ftp的下载
    nessus 漏洞扫描安装和使用
    实战medusa暴力破解
    浅谈python 中正则的一些函数
    一句话木马和中国菜刀的结合拿webshell
    浅说套接字socket做个小小的监控
    小巧的ssh客户端
    统计字符串的数字,英文字母,空格及其他的个数
    mysql字符串函数
  • 原文地址:https://www.cnblogs.com/abc-begin/p/7538288.html
Copyright © 2011-2022 走看看