Remove duplicates from Sorted Array I
Given a sorted array, remove the duplicates in place such, all element appear only once and return the new length.
Do the allocate extra space for another array, and you must does this on place with constant memory.
Example
Given input Array A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
Analysis:
With the pointer p pointing to the first number, and then with the other pointer I point to the second number, if P and I refer to the same number, I move down, if different, the number I refers to the position of the p+1.
1 Public classSolution {2 /**3 * @param a:a array of integers4 * @return: Return an integer5 * cnblogs.com/beiyeqingteng/6 */7 Public intRemoveDuplicates (int[] nums) {8 if(Nums = =NULL|| Nums.length = =0)return 0;9 Ten intp =0; One for(inti =1; i < nums.length; i++) { A if(Nums[i]! =Nums[p]) { -p++; -NUMS[P] =Nums[i]; the } - } - returnP +1; - } +}
Remove duplicates from Sorted Array II
Follow up for "Remove duplicates":
What if duplicates is allowed at the 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]
.
Analysis: The idea of solving problems as above, with Duplicatecount to keep track a number of repeated occurrences.
1 Public classSolution {2 /**3 * @param a:a array of integers4 * @return: Return an integer5 * Reprint Please specify source: cnblogs.com/beiyeqingteng/6 */7 8 Public intRemoveDuplicates (int[] nums) {9 if(Nums = =NULL|| Nums.length = =0)return 0;Ten One intDuplicatecount =1; A intp =0; - for(inti =1; i < nums.length; i++) { - if(Nums[i] = =Nums[p]) { the if(Duplicatecount <2) { -duplicatecount++; -p++; -NUMS[P] =Nums[i]; + } -}Else { +Duplicatecount =1; Ap++; atNUMS[P] =Nums[i]; - } - } - returnP +1; - } -}
Reprint Please specify source: cnblogs.com/beiyeqingteng/
Remove Duplicates from Sorted Array