给定一个已排序的数组,使用就地算法将重复的数字移除,使数组中的每个元素只出现一次,返回新数组的长度。
不能为数组分配额外的空间,你必须使用常数级空间复杂度的就地算法。
例如,给定输入数组 A=[1,1,2],
你给出的函数应该返回length=2,A数组现在是[1,2]。
public class Solution31 {
public int removeDuplicates(int[] A) {
// TODO Auto-generated constructor stub
if(A==null||A.length==0)
return 0;
int one=0,two=1;
int count=1;
while(one<A.length&&two<A.length) {
if(A[one]!=A[two]) {
A[count++]=A[two];
}
one++;
two++;
}
return count;
}
} import java.util.Arrays;
public class Solution {
public int removeDuplicates(int[] A) {
if(A == null || A.length == 0)
return 0;
int len = A.length;
int k = A[0];
int j = 1;
for(int i = 1; i < A.length ; i++){
if(A[i] == k){
len--;
}
else{
k = A[i];
A[j] = A[i];
j++;
}
}
return len;
}
}
public int removeDuplicates(int[] nums) { int i = 0; for (int n : nums) if (i == 0 || n > nums[i-1]) nums[i++] = n; return i; }
And to not need the i == 0 check in the loop:
public int removeDuplicates(int[] nums) { int i = nums.length > 0 ? 1 : 0; for (int n : nums) if (n > nums[i-1]) nums[i++] = n; return i; }