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 nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
本质就是在原有数组中把重复的数放到后面。
基本思路就是把重复的和不重复的交换,让重复的一直往后走,最后不重复的都放在前面。但是交换有点太浪费时间,所以改成复制。
所以需要维护两个指针(一个放当前最后一个不重复的数c,一个一直往前走m),和一个value值(放当前最后一个不重复的值,可以和第一个指针合并)。
public int removeDuplicates(int[] nums) {
if(nums.length == 0) return 0;
int length = 0;
int v = 0, m = 0, c = 0;
v = nums[0];
while(m < nums.length){
if(nums[m] == v) m++;
else{
c++;
nums[c] = nums[m];
v = nums[m];
}
}
length = c + 1;
return length;
}
基本上就是这样了,Java 跑好慢。。。
161 / 161 test cases passed.
Status: Accepted
Runtime: 428 ms