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 =
Given input array A =
[1,1,2]
,
Your function should return length =
2
, and A is now [1,2]
.
Idea:
If use the native idea, it will cost O(n^2) time and constant space. But will lead to time limit exceed. The code is below:
int removeDuplicates(int A[], int n) { if(n < 2) return n; int i = 0; while(i < n - 1){ int j = i; while(A[j] == A[j+1]){ j++; } if(j!=i){ int s = i+1; for(int k = j; k < n; k ++){ A[s] = A[k]; s++; } n = n - (j-i); } i++; } return n; }
============================================================================
Then I changed to another method and it passed the tests: Time complexity is O(n)
1. make each value in the array = current val - previous val;(This part need to be done from the end.)
2. find zeros and change that to valid values.
int removeDuplicates(int A[], int n) { if(n < 2) return n; for(int cur = n-1; cur > 0; --cur) A[cur] -= A[cur-1]; int i = 1; for (int j = 1; j < n; ++ j) if (A[j]) { A[i] = A[i - 1] + A[j]; ++ i; } return i; }
No comments:
Post a Comment