Remove Duplicates from Sorted Array I
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]
.
错误解答:
public class Solution { public int removeDuplicates(int[] A) { int length = A.length; if(length==0 || length==1) return length; for(int i=1; i<length;i++){ if(A[i-1]==A[i]){ for(int j=i; j<length-1; j++) A[j]=A[j+1]; //A[length-1]='\0'; length--; i--; } } return length; } }
虽然答案正确,但是O(n)为n的平方,time limit exceeded。
Solution:
public class Solution { public int removeDuplicates(int[] A) { int length = A.length; if(length==0 || length==1) return length; int next=1; length=1; for(int i=1; i<A.length;i++){ if(A[i-1]!=A[i]){ A[next] = A[i]; next++; length++; } } return length; } }
这种方法只需遍历一次,分别把只出现了一次的数填到A[next]里,时间复杂度为O(n)。
Remove Duplicates from Sorted Array II
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
Solution1:
public class Solution { public int removeDuplicates(int[] A) { int length = A.length; if(length<3) return length; int times =0; for(int i=1; i< length;i++){ if(A[i-1]==A[i]) times++; else{ times=0;} if(times>=2){ for(int j=i; j<length-1; j++){ A[j] = A[j+1]; } //A[length-1]= '\0'; times--; i--; length--; } } return length; } }
这种方法一发现重复两次以上的元素就删掉该元素,将后面元素整体往前移。虽然通过了,但时间复杂度为n的平方,不是很好的方法。
Solution2:
public class Solution { public int removeDuplicates(int[] A) { int length = A.length; if(length<3) return length; int times=0, next=1; length=1; for(int i=1; i< A.length;i++){ if(A[i-1]==A[i]) times++; else{ times=0;} if(times<2){ A[next]=A[i]; next++; length++; } } return length; } }
这种方法只需遍历数组一次,时间复杂度为O(n)。用times记录一个元素重复次数,用next记录移动完的下标,用length记录移动完的长度。如果times<2,就将A[i]的值移动到A[next],否则什么也不做,只移动下标i。
Note:
看其他同学的答案,有些将新生成的数组尾设为‘\0‘,如代码中注释语句所示。其实在java中数组没有结束符,即使将数组尾设为‘\0‘,数组也不会结束,而是将其中元素值设为0。这道题中改动后的数组主要由数组中元素和返回的int值,也就是数组的新长度决定。