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]
.
最初思路, 逐个检查数组元素, 如果发现当前元素值跟下一个元素值相同, 则跳开下一元素, 将下一元素后面的所有元素都前移一位. 于是这需要两个loop, 第一个是遍历所有数组元素, 第二个是在发现相同元素后后面所有元素前移. 于是时间复杂度为O(n*n), 验证过程中不断提示超时.
参考网上得到两个信息:
1. 数组结构一经建立不能更改(数组元素无法移除)
2. 可以用一个counter记录不重复的数组元素数目并作为返回值而不需要耿直地使用.length.
于是, 解题思路为:
1. 定义一个counter用于记录不重复的数组元素数目, 定义一个pointer作为数组指针
2. 如果发现当前数组元素跟上一个数组元素相等, 数组指针右移一位, counter不变.
3. 如果发现当前数组元素跟上一个数组元素不等, counter+1, 将正在检验的数组元素放入数组的第counter个数组元素, pointer右移一位.
Remark: 该思路其实相当于是重用原数组作为一个新数组设置不重复的数组元素, "新数组"元素指针用counter, 原数组元素指针用pointer.
public class Solution {
public int removeDuplicates(int[] A) {
// exception case
if (A.length <= 1) return A.length;
int count = 1; // counter
int point = 1; // pointer
while (point < A.length){
if (A[point] == A[point-1])
point++;
else {
count++;
A[count-1] = A[point];
point++;
}
}
return count;
}
}