码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode [80]Remove Duplicates from Sorted Array II

时间:2019-04-03 12:22:28      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:排序数组   NPU   hat   shm   忽略   style   ted   lis   etc   

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)

  

leetcode [80]Remove Duplicates from Sorted Array II

标签:排序数组   NPU   hat   shm   忽略   style   ted   lis   etc   

原文地址:https://www.cnblogs.com/xiaobaituyun/p/10647930.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!