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.
思路:很笨
记不太清自己的思路了。
class Solution {
public int removeDuplicates(int[] nums) {
int global = 0 ;
int j = 0;
for(int i = 0;i < nums.length;){
if(nums.length == 0){
return 0;
}
else if(nums.length == 1){
nums[0] = nums[0];
return 1;
}
else{
if((i+1)<nums.length&&nums[i] == nums[i+1]){
j = i + 1;
int count = 0;
while(j<nums.length&&nums[i] == nums[j]){
count ++;
j ++;
}
nums[global++] = nums[i + count];
i = j;
}
else{
nums [global++] = nums[i];
i++;
}
}
}
return global;
}
}
后记
把后面的一道题做了之后思路清晰了很多
用两个指针,i和j,i是慢的,j是快的
两两比较,但是需要注意的就是两两比较下来能确定的只有一个。所以,需要对数组的首个元素或者是末尾元素做一个判断。
我是将两两比较的元素的后面一个元素作确定,所以最开始需要对数组的首个元素做判断。
伪代码:
当数组为空时,则直接返回0;
当数组的长度为1时,直接返回1;
当数组长度大于1时,这种情况下,新的数组至少长度大于1,即至少有一个元素。于是,首先将数组的收割元素确定为新数组的首个元素。对第二个及之后的元素进行判断。nums[j]和nums[j+1](j的初始值为0,因为两两比较确定第二个的值,也就是确定从索引为大于等于1的值)的值作比较,如果相等,则直接跳过;如果不相等,则将后面的那个值nums[j]赋给nums[i],同时新数组的长度i增加1。
class Solution {
public int removeDuplicates(int[] nums) {
int i = 1;
if(nums.length==0){
return 0;
}
else if(nums.length == 1){
return 1;
}
else{
nums[0]= nums[0];
for(int j =0;j<nums.length-1;j++){
if(nums[j]!=nums[j+1]){
nums[i] = nums[j+1];
i++;
}
}
}
return i;
}
}
leetcode网站上给出的solution
思路:也是采用了两个计数器,i和j,i为慢的,j为快的
但是我没有想到的就是,因为慢的一定会比快的慢,而且是已经确定下来了的,所以可以直接把快的和慢的表示的元素直接比较。这样很节省。
要注意的是,慢的表示的是数组的所以,最后输出的数组长度时,需要对它加1。
class Solution{
public int removeDuplicates(int nums[]){
if(nums.length == 0){
return 0;
}
int i =0;
for(int j = 1;j<nums.length;j++){
if(nums[j]!=nums[i]){
i++;
nums[i] = nums[j];
}
}
return i+1;
}
}