首页 > 代码库 > 【LEETCODE】:Sort Characters By Frequency

【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