首页 > 其他 > 详细

Remove Duplicates from Sorted Array II

时间:2014-02-17 09:32:09      阅读:297      评论:0      收藏:0      [点我收藏+]

http://oj.leetcode.com/problems/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].

Solution:

由于数组已经排序,所以只需要增加一个变量来记录元素出现的次数;若没有排序,需要使用hash来记录每个元素的出现次数。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(0==n) return 0;
 5         int appear =1;
 6         int index =0;
 7         for (int i=1;i<n;++i){
 8             if (A[index]==A[i]){
 9                 if (appear<2){
10                     A[++index]=A[i];
11                     ++appear;
12                 }
13             }else{
14                 A[++index]=A[i];
15                 appear =1;
16             }
17         }
18         return index+1;
19         
20     }
21 };
bubuko.com,布布扣

Remove Duplicates from Sorted Array II

原文:http://www.cnblogs.com/fengyunyu/p/3551743.html

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