初级算法-数组-从排序数组中删除重复项

LeetCode还是很人性化的  用到什么算法竟然还会提示并有百度百科的链接  此题用到了原地算法,就是输出结果覆盖输入结果,节省空间,附上代码,C语言,代码写的渣,还参考了网上的答案,如有哪里需要改进还请斧正!

#include <stdio.h>
int removeDuplicates(int* nums, int numsSize)
{
    int pre = 0, cur = 0;
    if (numsSize == 0)
        return 0;
    while (cur < numsSize)
    {
        if (nums[pre] == nums[cur])
        {
            cur++;
        }
        else
        {
            nums[++pre] = nums[cur++];
        }
    }
    return pre + 1;
}
int main()
{
    int nums[1000];
    int num, i = 0;
    while (~scanf("%d", &num))
    {
        nums[i] = num;
        i++;
    }
    removeDuplicates(nums, i);
}

https://blog.csdn.net/lizhidefengzi/article/details/70196058 在大佬博客中又学到了新姿势  c++11又有了for的新用法

And to not need the !i check in the loop:

int removeDuplicates(vector<int>& nums) {
    int i = !nums.empty();
    for (int n : nums)
        if (n > nums[i-1])
            nums[i++] = n;
    return i;
}
And to not need the !i check in the loop:

int removeDuplicates(vector<int>& nums) {
    int i = !nums.empty();
    for (int n : nums)
        if (n > nums[i-1])
            nums[i++] = n;
    return i;
}
    原文作者:排序算法
    原文地址: https://blog.csdn.net/czyifenfei/article/details/79748516
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞