[Leetcode] 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].

 

Tag:

Array; Two Pointers

 

体会:

这个题,主要是借用了《算法导论》QuickSort里面Partitioning 的模式,其实也就是Tag里面的双指针的感觉。让lastUniq一直指着最后一位是uniq element 的位置,然后让循环指针 i 去探测,一旦探测到新的uniq的,就lastUniq++,然后交换lastUniq和 i 所对应的元素,最后返回 lastUniq + 1就是长度。初始化的时候,lastUniq = -1。啊,简直和那个partition如出一辙啊!

 

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        // two pointers
        int lastUniq = -1;
        for (int i = 0; i < n; i++) {
            // only cares about uniq element
            if (A[i] != A[lastUniq]) {
                lastUniq++;
                A[lastUniq] = A[i];
            }
        }
        return lastUniq + 1;
    }
};

 

posted @ 2014-10-25 22:19  StevenCooks  阅读(137)  评论(0编辑  收藏  举报