首页 > 其他 > 详细

怎样防超时——Remove Duplicates from Sorted Array I&&II

时间:2015-09-16 15:48:45      阅读:186      评论:0      收藏:0      [点我收藏+]

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.接上题,增加一个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;
     }
 };

  

怎样防超时——Remove Duplicates from Sorted Array I&&II

原文:http://www.cnblogs.com/qiaozhoulin/p/4813273.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!