LeetCode 之 Remove Duplicates from Sorted Array

来源:互联网 发布:淘宝交保证金可以退吗 编辑:程序博客网 时间:2024/04/29 02:36
原题:

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

这个题其实比较扯谈,不仅要去掉重复的数字的数组大小,还要新的数组。。。尼玛是伪新数组好么。。。。

好吧,说下解题思路:

1 用两个指针(学渣哪懂pointer,尼玛直接给你俩int,作为数组的index),分别指向新数组的尾部当前检测的数组成员。新数组的尾部用 newArrayTail来指示,从0开始,这意味着第一个元素自动进入新的数组 。

2 用一个for来检测,for里的i从1开始,判断A[i]和A[newArrayTail]是否相等,不相等说明可以把A[i]放入新的数组,同时把数组大小扩大一个,同时尾部后移。

3 最后要注意返回的是newArrayTail+1 ,n维数组的最后一个是A[n-1].

class Solution {public:    int removeDuplicates(int A[], int n) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        if (n <= 1) return n;                int newArrayTail = 0;                for (int i = 1; i < n ;i ++){            //A[pre] = A[i];            if (A[i] != A[newArrayTail]){                //两者不相等,说明不是重复的数,结果加1                A[newArrayTail+1] = A[i];                newArrayTail+=1;            }        }        return newArrayTail+1;    }};