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)

  

猜你喜欢

转载自www.cnblogs.com/xiaobaituyun/p/10647930.html
今日推荐