Remove Duplicates from Sorted Array

Question

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

题解

使用两根指针(下标),一个指针(下标)遍历数组,另一个指针(下标)只取不重复的数置于原数组中。

C++

  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.size() <= 1) return nums.size();
  9. int len = nums.size();
  10. int newIndex = 0;
  11. for (int i = 1; i< len; ++i) {
  12. if (nums[i] != nums[newIndex]) {
  13. newIndex++;
  14. nums[newIndex] = nums[i];
  15. }
  16. }
  17. return newIndex + 1;
  18. }
  19. };

Java

  1. public class Solution {
  2. /**
  3. * @param A: a array of integers
  4. * @return : return an integer
  5. */
  6. public int removeDuplicates(int[] nums) {
  7. if (nums == null) return -1;
  8. if (nums.length <= 1) return nums.length;
  9. int newIndex = 0;
  10. for (int i = 1; i < nums.length; i++) {
  11. if (nums[i] != nums[newIndex]) {
  12. newIndex++;
  13. nums[newIndex] = nums[i];
  14. }
  15. }
  16. return newIndex + 1;
  17. }
  18. }

源码分析

注意最后需要返回的是索引值加1。

复杂度分析

遍历一次数组,时间复杂度 O(n), 空间复杂度 O(1).