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],
刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions
简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Your function should return length = 2, and A is now [1,2].
» Solve this problem
On the first thought, I wanted to start from the end of the array. Set two pointers, to compare the value that two pointers point to. If they equals to each other, then I will move all the elements after one step ahead. But, this is cost tooooo much time and complicated!
I found a really good solution online, which is to check value of elements from the beginning of the array. Compare the value of last elem in array, if equal, then skip, if not, add to the end of the array.
Because it only need to return the length of the new array, so we can set a counter to count how many elements we have added to the end of the array instead of moving elements.
maybe the following solution can be better, which avoid extra copy.
ReplyDeletepublic int removeDuplicates(int[] A) {
if(A == null) {
return 0;
}
int n = A.length;
if(n <= 1) {
return n;
}
int i = 0;
for(int j = 1; j < n; ++j) {
if(A[j] != A[i]) {
++i;
if(i != j) {
A[i] = A[j];
}
}
}
return i+1;
}