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

    class Solution {
    public:
        int removeDuplicates(int A[], int n) {
           if(!n)return NULL;  
            int num=1,i;  
            for(i=1;i<n;++i)  
                if(A[i]!=A[i-1])  
                    A[num++]=A[i];    
            return num;  
            
        }
    };
    

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

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

    Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

     

     ii.接上题,增加一个count变量来记录key出现的次数。

    class Solution {
    public:
         int removeDuplicates(int A[], int n) {
              // Start typing your C/C++ solution below
              // DO NOT write int main() function
              if (n == 0)
                  return 0;
                  
              int key = A[0];
             int count = 0;
             int start = 0;
             
             for(int i = 0; i < n; i++)
                 if (key == A[i])
                     count++;
                 else
                 {
                     for(int j = 0; j < min(2, count); j++)
                         A[start++] = key;
                     key = A[i];
                     count = 1;
                 }
                 
             for(int j = 0; j < min(2, count); j++)
                 A[start++] = key;
                 
           return start;
         }
     };
    

      

  • 相关阅读:
    【Java】快速排序、归并排序、堆排序、基数排序实现总结
    【Java】二分查找、插值查找、斐波那契查找的实现,及分析
    【Java】Java实现常见的七种排序
    【C】常见的排序
    栈,迷宫问题
    海量数据处理问题
    【C】 布隆过滤器BloomFilter
    哈希变形---位图
    C实现Hash表,链式结构
    C实现Hash表,开放定址法
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4813273.html
Copyright © 2011-2022 走看看