【LeetCode】马三来刷题之Remove Duplicates from Sorted Array

本文介绍了LeetCode第26题——有序数组去重问题,难度为Easy。要求在原地修改数组,使得每个元素仅出现一次,并返回新长度。文章提供了两种解题方法,包括使用unique()函数和数组逐个比较。

恢复刷题第二天,题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/ 

26. Remove Duplicates from Sorted Array

 
  • Total Accepted: 157568
  • Total Submissions: 454924
  • Difficulty: Easy

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.

For example,
Given input array 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.

Subscribe to see which companies asked this question


题目很简单,给定一个排序好的数组,把相同的元素从原来的位置移除,并且返回一个不包含重复元素的长度即可。

同样是用了两种方法过的这道题,分别是unique和数组逐个比较的办法。

方法一:使用unique()函数:

int removeDuplicates(vector<int>& nums) {
    //unique()函数将重复的元素放到vector的尾部 然后返回指向第一个重复元素的迭代器
    //再用erase函数擦除从这个元素到最后元素的所有的元素
    nums.erase(unique(nums.begin(),nums.end()),nums.end());
    return nums.size();
}
方法二:数组元素逐个比较:

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;
}

每天一道题,保持新鲜感,就这样~



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值