[leetcode_26] Remove Duplicates from Sorted Array

删除已排好序的重复的元素。
不许开辟额外的空间。
插排,交换顺序到队尾。
和上一个题有点点像。
一次AC,附上代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int count = 0;
        int now = A[0];
        for(int i = 1; i < n-count; i++) {
            if(now == A[i]) {
                for(int j = i+1; j < n-count; j++) {
                    int tmp = A[j];
                    A[j] = A[j-1];
                    A[j-1] = tmp;
                }
                count++;
                i--;
            } else {
                now = A[i];
            }
        }
        return n - count;
    }
};
Licensed under CC BY-NC-SA 4.0