【leetcode】删除数组中指定要求的重复的数字

1. 给定一个数组和一个值,删除该值的所有实例,并返回新长度。 不要为另一个数组分配额外的空间,您必须使用常量内存来进行此操作。

元素的顺序可以改变。

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

题解:

  int removeElement(vector<int>& nums, int val) {
        int begin=0;
        int end=nums.size();
   for(int i=0;i<end;++i)
   {
       if(nums[i]!=val)
       {
           nums[begin++]=nums[i];
       }
   }
    return begin;
    }

2.Remove Duplicates from Sorted Array II

从排序数组中删除重复数组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.

思路:已序数组超过2次去重,已序?
总结:两个指针下表=下标,一个用来遍历,一个用来将正确的元素放在正确的位置,
特别注意:
1.边界条件的判断,是否元素个数为0可以通过?
2.重复元素多于2个怎么解决?
3.怎么样不会崩溃?

int removeDuplicates(vector<int>& nums) {

      int size=0;  
        for(int i=0;i<nums.size();++i)
        {
            if(i<2)
            {
                size++;      
            }

            else if(nums[i]>nums[size-2])
            {
                nums[size++]=nums[i];
            }

        }
        return size;
    }

再来学习一下更新颖的解法:

int removeDuplicates(vector<int>& nums) {
    int i = 0;
    for (int n : nums)
        if (i < 2 || n > nums[i-2])
            nums[i++] = n;
    return i;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值