C++删除数组内重复的数据2011-04-04笔试时曾经遇到过的一道题,当时没有好的想法。今天无意中想起,于是把自己的一种解决方法记下来。1. main.cpp
1./**
2. * 问题描述:
3. * 删除数组内重复的数据
4. *
5. * 一个解决方法:
6. * 可以先将数组排序,然后再删除
7. * 如一个已经排好序的整数数组:1, 1, 2, 2, 3
8. */
9.
10.#include <iostream>
11.
12.using std::cout;
13.using std::endl;
14.using std::swap;
15.
16./**
17. * 打印数组
18. */
19.template<class T>
20.void printArray(const T array[], const int size);
21.
22./**
23. * 将数组排序,选择排序
24. */
25.template<class T>
26.void sort(T array[], const int size);
27.
28./**
29. * 对已经排好序的数据
30. * 将数组内重复的数据删除
31. * @return int 删除重复数据后数组的大小
32. */
33.template<class T>
34.int deleteRepeatedData(T array[], const int size);
35.
36.int main(int argc, char *argv[]) {
37.int array[] = {9, 1, 1, 8, 2, 3, 3, 4, 3, 3, 5, 9, 7, 8, 2, 6, 9, 1, 9, 0, 9, 0};
38.int size = sizeof(array) / sizeof(int);
39.cout<<"A initial int array: "<<endl;
40.printArray(array, size);
41.
42.cout<<"
After sort: "<<endl;
43.sort(array, size);
44.printArray(array, size);
45.
46.cout<<"
After delete repeated data: "<<endl;
47.size = deleteRepeatedData(array, size);
48.printArray(array, size);
49.}
50.
51./**
52. * 打印数组
53. */
54.template<class T>
55.void printArray(const T array[], const int size) {
56.for (int i=0; i<size-1; i++) {
57.cout<<array[i]<<", ";
58.}
59.cout<<array[size-1]<<endl;
60.}
61.
62./**
63. * 将数组排序,选择排序
64. */
65.template<class T>
66.void sort(T array[], const int size) {
67.for (int i=0; i<size-1; i++) {
68.int min = i;
69.for (int j=i+1; j<size; j++) {
70.if (array[min] > array[j]) {
71.min = j;
72.}
73.}
74.if (min != i) {
75.swap(array[i], array[min]);
76.}
77.}
78.}
79.
80./**
81. * 对已经排好序的数据
82. * 将数组内重复的数据删除
83. * @return int 删除重复数据后数组的大小
84. */
85.template<class T>
86.int deleteRepeatedData(T array[], const int size) {
87.int j = 0;
88.for (int i=0; i<size-1; i++) {
89.while (array[i] == array[i+1]) {
90.i++;
91.}
92.array[j++] = array[i];
93.}
94.return j;
95.}