温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++有序数组中去除重复项的方法

发布时间:2022-03-28 13:47:45 来源:亿速云 阅读:292 作者:iii 栏目:大数据

这篇文章主要讲解了“C++有序数组中去除重复项的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++有序数组中去除重复项的方法”吧!

有序数组中去除重复项

Example 1:

Given 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 respectively.

It doesn"t matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length =

7

, with the first seven elements of

nums

being modified to 

0

, 0, 1, 1, 2, 3 and 3 respectively.

It doesn"t matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

这道题是之前那道 Remove Duplicates from Sorted Array 的拓展,这里允许最多重复的次数是两次,那么可以用一个变量 cnt 来记录还允许有几次重复,cnt 初始化为1,如果出现过一次重复,则 cnt 递减1,那么下次再出现重复,快指针直接前进一步,如果这时候不是重复的,则 cnt 恢复1,由于整个数组是有序的,所以一旦出现不重复的数,则一定比这个数大,此数之后不会再有重复项。理清了上面的思路,则代码很好写了:

解法一:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int pre = 0, cur = 1, cnt = 1, n = nums.size();
        while (cur < n) {
            if (nums[pre] == nums[cur] && cnt == 0) ++cur;
            else {
                if (nums[pre] == nums[cur]) --cnt;
                else cnt = 1;
                nums[++pre] = nums[cur++];
            }
        }
        return nums.empty() ? 0 : pre + 1;
    }
};

这里其实也可以用类似于 Remove Duplicates from Sorted Array 中的解法三的模版,由于这里最多允许两次重复,那么当前的数字 num 只要跟上上个覆盖位置的数字 nusm[i-2] 比较,若 num 较大,则绝不会出现第三个重复数字(前提是数组是有序的),这样的话根本不需要管 nums[i-1] 是否重复,只要将重复个数控制在2个以内就可以了,参见代码如下:

解法二:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        for (int num : nums) {
            if (i < 2 || num > nums[i - 2]) {
                nums[i++] = num;
            }
        }
        return i;
    }
};

感谢各位的阅读,以上就是“C++有序数组中去除重复项的方法”的内容了,经过本文的学习后,相信大家对C++有序数组中去除重复项的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI