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

【LEETCODE】:Sort Characters By Frequency

时间:2017-04-21 00:41:20      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:str   and   目的   mem   tps   ==   most   rem   删除   

声明:该题目来自https://github.com/soulmachine,

一、Remove Duplicates from Sorted Array
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

给定一有序数组,删除该数组中重复出现的元素,返回新数组的长度。要求:不要分配额外的数组空间。

int removeDuplicates(vector<int>& nums) {
    if (nums.empty())
    {
        return 0;
    }
    int index = 0;
    for (int i = 1;i < nums.size();++i)
    {
        if (nums[index] != nums[i])
        {
            nums[index++] = nums[i];
        }
    }
    return index + 1;
}

 

int removeDuplicates2(vector<int>& nums) {
    return distance(nums.begin(), unique(nums.begin(), nums.end()));
}

 

二、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]

  只需要在第一个题目的基础上增加一个计数器即可完成。

int removeDuplicates(vector<int>& nums) {
    if (nums.empty())
    {
        return 0;
    }
    int index = 0;
    int count = 1;
    for (int i = 1; i < nums.size(); ++i)
    {
        if (nums[index] == nums[i])
        {
            if (count < 2)
            {
                count++;
                nums[index++] = nums[i];
            }
        }
        else
        {
            count = 1;
            nums[index++] = nums[i];
        }
    }
    return index + 1;
}

 

其他几种实现:

int removeDuplicates2(vector<int>& nums) {
    if (nums.size() <= 2)
        return nums.size();
    int index = 2;
    for (int i = 2;i < nums.size();++i)
    {
        if (nums[i] != nums[index - 2])
        {
            nums[index++] = nums[i];
        }
    }
    return index;
}
int removeDuplicates3(vector<int>& nums) {
    const int n = nums.size();
    int index = 0;
    for (int i = n; i < n;++i)
    {
        if (i > 0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1])
        {
            continue;
        }
        nums[index++] = nums[i];
    }
    return index;
}

 

【LEETCODE】:Sort Characters By Frequency

标签:str   and   目的   mem   tps   ==   most   rem   删除   

原文地址:http://www.cnblogs.com/willkall/p/6741203.html

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