Remove Duplicates from Sorted Array 有序数组删除重复元素 @LeetCode

本文详细介绍了如何在排序数组中去除重复元素,并提供了变型题的解决思路,通过前后指针的方法实现原地操作,优化算法效率。

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

题目:

给定一个排序过的数组,要求in place的移除重复元素,返回处理后的数组长度


思路:

前后指针,一遍遍历数组即可


变型题是:移除元素后,使得重复出现的元素最多出现2次

http://blog.youkuaiyun.com/fightforyourdream/article/details/12883543



/**
 * 
 * Remove Duplicates from Sorted Array
 *  
 * 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].
 * 
 */
public class S26 {

	public static void main(String[] args) {
		int[] A = {1, 1, 2};
		System.out.println(removeDuplicates(A));
	}
	
	public static int removeDuplicates(int[] A) {
		int len = A.length;
        if(len < 2){
        	return len;
        }
        
        // i遍历数组,j指向待检验是否与i相同的下一个数
        int i = 0, j = 1;
        while(i<len && j<len){
        	if(A[i] == A[j]){		// 如果出现相同
        		j++;		// 则j继续往前找,直到找到不同于A[i]数
        	}else{
        		i++;		// i跳动要被覆盖的重复那个数
        		A[i] = A[j];		// 用非重复的j覆盖重复的i
        		j++;		// 更新待检验的j
        	}
        }
        
        // 返回长度是下标加1
        return i+1;
    }

}



public class Solution {
    public int removeDuplicates(int[] A) {
        int len = A.length;
        if(len <= 1){
            return len;
        }
        int p = 0, q = 0;
        while(q < len){
            if(A[p] == A[q]){
                q++;
            }else{
                p++;
                A[p] = A[q];
                q++;
            }
        }
        return p+1;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值