2.1.1—线性表—Remove Duplicates from Sorted Array

来源:互联网 发布:青岛乐智网络 编辑:程序博客网 时间:2024/06/07 13:04
描述
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].

#include<iostream>using namespace std;int DeleteDuplicate(int a[], int n){if (a == NULL || n <= 0)return -1;int i = 0;int j = 1;for (; j < n;){if (a[i] != a[j]){i++;a[i]= a[j];j++;}else{while (a[i] == a[j])j++;}}return i + 1;}int main(){const int n = 10;int a[n] = { 1,1, 2,2,2,2, 3,3,3, 5 };int k = DeleteDuplicate(a, n);for (int i = 0; i < k; i++)cout << a[i] << " ";cout << endl;}


阅读全文
0 0
原创粉丝点击