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].
没有想通为什么这个简单的问题竟然不是那么简单,太小看它了,以下是别人的很不错的solution:
Solution: 做法是维护两个指针,一个保留当前有效元素的长度,一个从前往后扫,然后跳过那些重复的元素。因为数组是有序的,所以重复元素一定相邻,不需要额外记录。时间复杂度是O(n),空间复杂度O(1)。代码如下:
1 public class Solution { 2 public int removeDuplicates(int[] A) { 3 if(A == null || A.length==0) 4 return 0; 5 int index = 1; 6 for(int i=1;i<A.length;i++) 7 { 8 if(A[i]!=A[i-1]) 9 { 10 A[index]=A[i]; 11 index++; 12 } 13 } 14 A = Arrays.copyOf(A, index); 15 return index; 16 } 17 }
1 class Solution { 2 public int removeDuplicates(int[] nums) { 3 int index = 1; 4 for (int i = 1; i < nums.length; i ++) { 5 if (nums[i] != nums[index - 1]) { 6 nums[index ++] = nums[i]; 7 } 8 } 9 return index; 10 } 11 }