// test14.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<exception>
#include <initializer_list>
using namespace std; class Solution {
public:
// Parameters:
//numbers: an array of integers
//length: the length of array numbers
//duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) { int k = 0;//统计duplication数组中的元素个数
bool result = false; //返回结果 //对numbers数组进行排序
for (int i = 0; i < length; i++)
{
for (int j = i+1; j < length; j++)
{
if (numbers[i] > numbers[j])
{
int t = numbers[j];
numbers[j] = numbers[i];
numbers[i] = t;
}
} } //cout << "numbers:";
//for (int i = 0; i < length; i++)
//{
// cout << numbers[i] << " ";
//}
//cout << endl; int temp = numbers[0]; for (int i = 1; i < length; i++)
{
if (temp == numbers[i])//如果有重复
{
if(k==0)//duplication中没有数据进行的处理
{
duplication[k++] = temp;
result = true;
} else if (temp != duplication[k - 1])//duplication中有数据要进行的判断,如果没有存储,需要存储
{
duplication[k++] = temp;
result = true;
}
else // duplication中有数据要进行的判断,如果已经存储,不需要做处理
{
result = true;
} }
else//如果和之前数据没有相同的,temp等于这个数据
{
temp = numbers[i];
} } /* cout << "duplication:";
for (int i = 0; i < k; i++)
{
cout << duplication[i] << " ";
}
cout << endl;*/ return result; }
}; int main()
{
int a[7] = { 2,3,1,0,2,5,3 };
int b[7] = { 0 };
int* duplication=b;
Solution so;
so.duplicate(a, 7, duplication); return 0;
} 思路:先排序,然后统计计算
03-31 15:53