leetcode: Remove Duplicates from Sorted Array

http://oj.leetcode.com/problems/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].

思路

如果有一个数需要被删掉,那就意味着他后面的数如果需要保留的话就得往前移动一步,已经删掉n个数后,需要被保留的数要往前移动n步。加一个变量记录被删掉的元素个数就解决了。

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         int len = n, step = 0;
 5         
 6         for (int i = 1; i < n; ++i) {
 7             if (A[i] == A[i - 1]) {
 8                 ++step;
 9                 --len;
10             }
11             else {
12                 A[i - step] = A[i];
13             }
14         }
15         
16         return len;
17     }
18 };
原文地址:https://www.cnblogs.com/panda_lin/p/remove_duplicates_from_sorted_array.html