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].
solution:
①需要返回重构的A的长度②检验返回长度内,A是否已经没有重复(长度外数据不考虑)
·条件②表明,我们不用考虑长度外的数据,只需要保证长度内的数据无重复且sorted(有序)即可,因此长度内的数据遇到重复时可以使用长度外的不重复数据进行覆盖。
·两个参数,一个i用来从前向后循环数组,一个index(从0开始)用来记录最后一个没有重复的数字的位置。当index位置后面出现不重复的数字,将index值加一并附新的不重复值,当index后面全部重复出现,则index+1就是不重复数组长度。
·考虑空集和只有一个元素的数组(可以整合进去)
code:
<span style="color:#333333;">public class Solution {
public int removeDuplicates(int[] A) {
int index = 0;
int length = A.length;
if (</span><span style="color:#ff0000;">length == 0</span><span style="color:#333333;">) {
return 0;
}else {
for (int i = 1; i < length; i++) {
if (A[i] == A[index]) {
</span><span style="color:#ff0000;">continue;</span><span style="color:#333333;">
}else {
</span><span style="color:#ff0000;">index++;
A[index] = A[i]; //直接覆盖</span><span style="color:#333333;">
}
}
return index+1;
}
}
}</span>

本文介绍了一个算法,用于在不使用额外空间的情况下,去除数组中的重复元素,并返回处理后的数组长度。该算法通过双指针技巧实现,确保数组内部元素唯一且有序。
493

被折叠的 条评论
为什么被折叠?



