Remove Duplicates from Sorted Array
Question
-
lintcode: (100) Remove Duplicates from Sorted Array
- 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 should return length = 2, and A is now [1,2].
-
- Example
-
- Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
題解
使用雙指標(下標),一個指標(下標)遍歷vector數組,另一個指標(下標)只取不重複的數置於原vector中。
1. class Solution {
2. public:
3. /*
4. * @param A: a list of integers
5. * @return : return an integer
6. /
7. int removeDuplicates(vector
8. if (nums.empty()) {
9. return 0;
10. }
11. 12. int size = 0;
13. for (vector
14. if (nums[i] != nums[size]) {
15. nums[++size] = nums[i];
16. }
17. }
18. return ++size;
19. }
20. };
源碼分析
注意最後需要返回的是++size或者size + 1
