Remove duplicates from sorted array I
Given a sorted array, remove the duplicates in place such that each element appear onlyOnceAnd 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 shocould return length =2
, And a is now[1,2]
.
Remove duplicates from sorted array II
Follow up for "remove duplicates ":
What if duplicates are allowed at mostTwice?
For example,
Given sorted array A =[1,1,1,2,2,3]
,
Your function shocould return length =5
, And a is now[1,1,2,2,3]
.
Personal thoughts:
1. Think of the entire array as two parts. The first half is an array that meets the requirements of the question, and the second half is an array to be explored. set two variables for traversal: Index and I, index is used to locate the end of the first half of the array, and I is used to locate the array of the second half. The elements between the two parts are excluded elements.
2. At the same time, set a variable count to record the number of repetitions, and set another variable limit to record the maximum number of repetitions. In this case, there are four cases, when a [Index] = A [I], count is greater than limit or count is not greater than limit, a [Index]! = A [I], count is greater than limit or count is not greater than limit
3. I traversal is used to continuously add elements that meet the requirements of the question to the first half of the array.
Code:
1 class solution {2 public: 3 int removeduplicates (int A [], int N) {4 5 If (n <2) 6 {7 return N; 8} 9 10 const int Limit = 2; // set I to 1, II to 211 int Index = 0, I = 1, Count = 1; 12 13 while (I <n) 14 {15 if (a [Index] = A [I]) 16 {17 + count; 18 if (count> limit) 19 {20 + I; 21} 22 else23 {24 A [++ Index] = A [I ++]; 25} 26} 27 else28 {29 A [++ Index] = A [I ++]; 30 COUNT = 1; 31} 32} 33 34 return index + 1; 35} 36 };
View code
Through these two questions, we can summarize a general method for processing arrays (requiring the space complexity to be a constant), that is, the entire array is regarded as two parts, and the first part meets the requirements, you need to use a variable to locate this part. The latter part is to be processed and located and traversed through a variable, there may be surplus elements in the two parts (this part is not suitable for processing). By traversing the elements in the latter part, the array of the former part will be expanded continuously, the entire process is completed after all the elements in the last part are traversed.
Leetcode-remove duplicates from sorted array I & ii