码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Remove Duplicates from Sorted Array II

时间:2015-06-04 11:30:48      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

Problems:

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.

解法一:在Remove Duplicates from sorted Array的基础上加入计数count用来判断重复的次数

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

解法二:

代码简洁聪明

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        
        if(nums.size()<=2)  return n;
        
        int index=2;
        for(int i=2;i<nums.size();i++)
        {
                if(nums[i]!=nums[index-2])
                   nums[index++]=nums[i];
         }
                
          return index;      
               
    }
};

 

LeetCode:Remove Duplicates from Sorted Array II

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4551109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!