Package Cn.edu.xidian.sselab.array;
/** * * @author Zhiyong Wang * Title:remove duplicates from Sorted Array * Content: * Given a sorted array, remove the duplicates in place such, all element appear only once and return the new length. * Do not allocate extra space for another array, and you must does this on place with constant memory. * For example, * Given input array nums = [1,1,2], * Your function should return length = 2, with the first of the elements of Nums being 1 and 2 respectively. It doesn ' t matter what are you leave beyond the new length. */ public class Removeduplicatesfromsortedarray {
This problem is almost the same as removeelement, because it is an array that has been sequenced, and the comparison condition is changed to the adjacent two numbers. Also is the logarithm of the number of the statistic double, the number of the same number of each number forward But when compared to pay attention to the problem, do not cross the border, here is particularly important, nums inside the number of less than 2 times, do not do any processing, only more than 1 will be compared public int removeduplicates (int[] nums) { int length = Nums.length; int count = 0; if (length>1) { for (int i=1;i<length;i++) { if (nums[i-1] = = Nums[i]) { count++; }else{ Nums[i-count] = nums[i]; } } } return length-count; } }
|
?
Remove duplicates from Sorted Array