LeetCode每日一题:remove duplicates f
2017-05-18 本文已影响8人
yoshino
问题描述
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].
问题分析
剔除重复元素,不能使用额外的空间和新的数组,用count计数,遇到不重复的加入原先数组进行覆盖即可
代码实现
public int removeDuplicates(int[] A) {
if (A.length == 0 || A.length == 1) return A.length;
int count = 1;
for (int i = 1; i < A.length; i++) {
if (A[i] != A[i - 1]) {
A[count] = A[i];
count++;
}
}
return count;
}