LeetCode 26. Remove Duplicates from Sorted Array && 80. Remove Duplicates from Sorted Array II

来源:互联网 发布:mac桌面双桌面用 编辑:程序博客网 时间:2024/05/17 17:43

LeetCode 26. 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 by modifying the input array in-place with O(1) extra memory.

Example:Given nums = [1,1,2],Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.It doesn't matter what you leave beyond the new length.

从有序数组中去重,元素允许的最大重复次数是一次。不允许分配额外的空间制造新的数组,只能直接在原数组上进行修改。在数组中删除某个元素的含义是:将这个元素放到size之外。比如:[1,1,2],就将其变为:[1,2,1]或[1,2,2],然后返回size为2即可。size范围之外的东西,不必考虑,那就等于删除。

这里我使用Two Pointers,cur指向不重复数组的尾部,i用来遍历整个数组,一旦遇到不重项,就将cur+1所指位置赋值为该不重复项。最后返回的结果:不重复数组的长度=cur+1。

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

LeetCode 80. Remove Duplicates from Sorted Array II

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的扩展,不同的是元素允许的最大重复次数是两次。因此数组[1,1,1,2,2,3]最后保留的是[1,1,2,2,3]。

我根据上一道题的解法,稍作调整。当元素重复了两次后就用一个变量dup记录该元素的值,如果下一个元素和dup相等的话,迭代指针直接向前移动,从下下一个元素开始新一轮比较。

int removeDuplicates(vector<int>& nums) {        if (nums.size() < 2) return nums.size();        int dup = nums[0] - 1, cur = 0;        for (int i = 0; i < nums.size() - 1; i++) {            if (dup == nums[i + 1]) continue;            if (nums[i] == nums[i + 1]) dup = nums[i + 1];            ++cur;            nums[cur] = nums[i + 1];        }        return cur + 1;    }

更简洁的解法:直接比较当前元素和新数组倒数第二个元素。

int removeDuplicates(vector<int>& nums) {        int n = nums.size();        if (n < 3)            return n;        int i = 0, newSize = 2;        for (i = 2; i < n; i++)        {            if (nums[i] != nums[newSize-2])                nums[newSize++] = nums[i];        }        return newSize;    }

更加通用的解法(适用于允许数组元素重复k次):
https://discuss.leetcode.com/topic/7673/share-my-o-n-time-and-o-1-solution-when-duplicates-are-allowed-at-most-k-times

阅读全文
0 0
原创粉丝点击