Remove Duplicates from Sorted Array leetcode java

本文介绍了一个去除已排序数组中重复元素的算法实现。通过双指针技术,该算法能够在常数空间复杂度下完成任务,即不使用额外的存储空间。文章提供了具体的Java代码示例,展示了如何仅通过修改原始数组来移除重复项并返回新的有效长度。

摘要生成于 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].

 

题解:

题目关键字:数组,已排好序的,只能in place替换,不能用额外数组,并且要求结果返回unique的长度。

题解方法是双指针,一个指针只记录unique的并且帮助记录长度,一个指针往前找。

代码如下:

 1     public int removeDuplicates(int[] A) {
 2         if(A.length == 0 || A == null)
 3             return 0;
 4         
 5         int len = 1;
 6         for(int index = 1; index < A.length; index++){
 7             if(A[index] != A[index-1]){
 8                 if(A[index] != A[len])
 9                     A[len] = A[index];
10                 len++;
11             }
12         }
13         return len;
14     }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值