Remove Duplicates from Sorted Array

来源:互联网 发布:软件开发精品课程 编辑:程序博客网 时间:2024/06/05 23:05

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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:双指针,数组的原地操作。

#include <iostream>using namespace std;int removeDuplicates(int A[], int n){    if(A == NULL || n == 0)        return 0;int i = 0;int j = 0;while(1){if(j == 0 || A[j] != A[j - 1]){A[i++] = A[j++];}else j++;if(j >= n)break;}return i;}int main(){int num[] = {1, 1, 1, 2, 2, 3};int n = removeDuplicates(num, sizeof(num) / sizeof(int));for(int i = 0; i < n; i++)cout<<num[i]<<" ";}

0 0
原创粉丝点击