首页 > 其他 > 详细

[Leetcode] Remove Duplicates From Sorted Array

时间:2014-10-25 22:56:25      阅读:362      评论:0      收藏:0      [点我收藏+]

题目:

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;
    }
};

 

[Leetcode] Remove Duplicates From Sorted Array

原文:http://www.cnblogs.com/stevencooks/p/4051059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!