Remove Duplicates from Sorted Array

Question

  1. Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
  2. Do not allocate extra space for another array, you must do this in place with constant memory.
  3. For example,
  4. Given input array A = [1,1,2],
  5. Your function should return length = 2, and A is now [1,2].
  6. Example

題解

使用雙指標(下標),一個指標(下標)遍歷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<int> &nums) {
  8. if (nums.empty()) {
  9. return 0;
  10. }
  11. int size = 0;
  12. for (vector<int>::size_type i = 0; i != nums.size(); ++i) {
  13. if (nums[i] != nums[size]) {
  14. nums[++size] = nums[i];
  15. }
  16. }
  17. return ++size;
  18. }
  19. };

源碼分析

注意最後需要返回的是++size或者size + 1