LeetCode—Remove Duplicates from Sorted Array

来源:互联网 发布:淘宝店铺流量100 编辑:程序博客网 时间:2024/06/15 16:15

题目:

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

解题思路:从数组的末尾开始,比较前一元素和当前元素,相等则向前移动一个位置,最后返回数组大小n,代码如下:

#include "stdafx.h"#include <iostream>using namespace std;int removeDuplicates(int A[], int n) {for (int i = n-1; i>0;i--){if (A[i - 1] == A[i]){for (int j = i-1 ; j < n; j++){A[j] = A[j + 1];}n--;}}return n;}int _tmain(int argc, _TCHAR* argv[]){int a[] = { 1, 2, 3,3 };cout << removeDuplicates(a, 4)<<endl;return 0;}


0 0