LeetCode Remove Duplicates from Sorted Array, leetcodeduplicates
Remove Duplicates from Sorted Array Total Accepted: 52196 Total Submissions: 165553 My Submissions Question Solution
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],
Your function shocould return length = 2, and A is now [1, 2].
Delete duplicate elements in an ordered array
Code 1:
class Solution {public: int removeDuplicates(int A[], int n) { if(n==0)return 0; int index=0; for(int i=1;i<n;++i) { if(A[i]!=A[i-1]) A[++index]=A[i]; } return index+1; }};
161/161 test cases passed.
Status: Accepted
Runtime: 37 MS
Code 2 (network retrieval ):
// LeetCode, Remove Duplicates from Sorted Array // use STL, time complexity O (n), space complexity O (1) class Solution {public: int removeDuplicates (int A [], int n) {return distance (A, unique (A, A + n ));}}
161/161 test cases passed.
Status: Accepted
Runtime: 34 MS
In STL, the unique function is a deduplicated function. The unique function is used to remove adjacent duplicate elements (only one record is retained). In fact, it does not actually Delete duplicate elements, is to move the repeated elements to the back, and then save them to the original array, and then return the address of the last element after deduplication, because unique removes adjacent repeated elements, therefore, we usually sort the order before using it.
Distance returns the distance between two iterators.