LEETCODE:Sort Characters By Frequency

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LEETCODE:Sort Characters By Frequency相关的知识,希望对你有一定的参考价值。

声明:该题目来自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的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode sort]75. Sort Colors

[leetcode sort]147. Insertion Sort List

LeetCode sort-list

javascript [选择排序] #LeetCode #Sort

javascript [选择排序] #LeetCode #Sort

LeetCode:Sort Colors