Topic
Follow up "Delete duplicate numbers":
What happens if two repetitions can be allowed?
Have you ever encountered this problem in a real interview? YesSample Example
To array a =[1,1,1,2,2,3], your function should return a length of 5, at which time a=[1,1,2,2,3].
The analysis and the idea of the same, only need to add a record element occurrences of the variable, the limit will occur up to 2 times.
Python code
Class solution: "" " @param a:a list of integers @return an integer " "" def removeduplicates (self, A ): # Write your code here if Len (a) = = 0: return 0 times = 1 k = 0 for i in range (1,len (A)):
if a[i]! = A[k]: k + + 1 a[k] = A[i] times = 1 else: if times >= 2: continue else:
k + = 1 a[k] = A[i] times + = 1 del A[k+1:len (a)] return Len (a)
GitHub-Python code
C + + code
/*101 Delete duplicate numbers in sorted array II follow up "delete duplicate numbers": What happens if two repetitions can be allowed? Have you ever encountered this problem in a real interview? The Yes sample gives the array a =[1,1,1,2,2,3], your function should return the length 5, at this time a=[1,1,2,2,3]. */class Solution {public:/** * @param a:a List of integers * @return: Return an integer */int remove Duplicates (vector<int> &nums) {//write your code here if (Nums.empty ()) {retur n 0; }//if int n = nums.size (), k=0, Times=1; for (int i=1; i<n; ++i) {if (nums[i]! = Nums[k]) {nums[++k] = nums[i]; times = 1; }else if (nums[i] = = Nums[k]) {if (Times >= 2) {continue; }else{Nums[++k] = nums[i]; ++times; }//else}//elif}//for nums.resize (k+1); return k+1; }};
GitHub--C + + code
Lintcode (101) Delete duplicate numbers in sorted array II