[LeetCode]Remove Duplicates from Sorted Array

本文介绍两种数组去重的方法,一种适用于已排序数组,另一种适用于无序数组。已排序数组通过一次遍历即可完成去重,而无序数组则利用HashMap记录出现过的元素,并使用Queue跟踪重复元素的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

将一个已排好序的数组中的重复元素去除,同时返回新的数组长度

解题思路


思路1:

因为所给数组已经是有序的,所以我们只需遍历一遍,遇到重复的跳过,遇到和前值不相等的,将其覆盖到前值的后一个位置。



思路2:

对于更为普遍的情况,如果数组是无序的,经过去重后数组仍按初始顺序排列,那么采用如下方法:

  1. 使用HashMap<Integer,Integer>来保存键值对<值,个数>,int类型的变量记录去重后数组的长度;
  2. 使用Queue<Integer>来记录重复数字的位置,将后续未重复的数填充到相应位置;

代码

思路1:

public static int removeDuplicates(int[] A) {
        int length = 1;
        if(A==null || A.length==0)
        	return 0;
        if(A.length==1)
        	return 1;
        
        int lastPos = 0;
        for(int i = 1;i < A.length;i++){
           while(i < A.length && A[i] == A[lastPos]){
        	   i++;
           }
           if(i < A.length){
        	   A[lastPos+1] = A[i];
               lastPos += 1;
               length++;
           }
        }
        
        return length; 	
	}


思路2:

public static int removeDuplicates(int[] A) {
        int length = 0;
        if(A==null || A.length==0)
        	return 0;
        if(A.length==1)
        	return 1;
        
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        Queue<Integer> posQueue = new ArrayDeque<Integer>();
        for(int i = 0;i < A.length;i++){
        	if(!map.containsKey(A[i])){
        		length++;
        		map.put(A[i], 1);
        		if(!posQueue.isEmpty()){
        			A[posQueue.poll()] = A[i];
        			posQueue.offer(i);
        		}
        	} else {
        		posQueue.offer(i);
        	} 
        }
        
        return length; 	
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值