LEETCODE: Remove Duplicates from Sorted Array

来源:互联网 发布:明源软件上海分公司 编辑:程序博客网 时间:2024/05/17 02:37
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].


 放在以前,我做这道题目也是很混乱的。现在一看,就是从后往前便利,如果有重复,算出新的长度,并且根据减少的元素个数调整当前位置后面的元素。


class Solution {public: int removeDuplicates(int A[], int n) {     if(A == NULL || n == 0) return 0;        int newLength = n;        for(int ii = n - 1; ii > 0; ii --) {            int jj = ii;            while(A[jj] == A[jj - 1] && jj  > 0) {                jj --;                newLength --;            }            if(jj != ii) {                for(int kk = jj + 1; kk < newLength; kk ++) {                    A[kk] = A[kk + (ii - jj)];                }ii = jj;            }        }                return newLength;    }};


0 0
原创粉丝点击