leetcode [80]Remove Duplicates from Sorted Array II

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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.

题目大意;

给一个排序数组,能否只使用O(1) 的额外空间在数组原地对数组进行处理,对重复数组超过3次以上的,换成出现两次。

解法:

看题目的时候忽略了只使用O(1)的额外空间,使用了一个hashmap来存储数组出现的次数,对出现三次及以上的按两次进行处理,遍历了两遍数组。

Java:

class Solution {
    public int removeDuplicates(int[] nums) {
        int n=nums.length;
        HashMap<Integer,Integer>m=new HashMap<Integer, Integer>();
        for(int i=0;i<nums.length;i++){
            if(m.get(nums[i])!=null) m.put(nums[i],m.get(nums[i])+1);
            else m.put(nums[i],1);
        }
        int i=0;
        int j=0;
        while(i<nums.length){
            if(m.get(nums[i])>2){
                nums[j]=nums[j+1]=nums[i];
                j+=2;
                i+=m.get(nums[i]);
                continue;
            }else {
                nums[j++]=nums[i++];
            }
        }

        return j;
    }
}

看了别人的解法,发现自己觉得这道题目复杂的原因还是因为自己太傻了。

Java:

不允许两个重复元素:

public int removeDuplicates(int[] nums) {
    int i = 0;
    for(int n : nums)
        if(i < 1 || n > nums[i - 1]) 
            nums[i++] = n;
    return i;
}

允许两个重复元素:

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

Python:

Python的内置函数就是爽啊,直接list.pop(i),删除list中的第i个元素。而java和c++都没有这样的骚操作。如果发现有三个及以上的,直接删除该元素。

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i=1
        isDup=False
        while i<len(nums):
            if not isDup:
                if nums[i]==nums[i-1]:
                    isDup=True
                i+=1
            else:
                if nums[i]==nums[i-1]:
                    nums.pop(i)
                else:
                    i+=1
                    isDup=False
        return len(nums)

  

转载于:https://www.cnblogs.com/xiaobaituyun/p/10647930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值