// 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;
}
思路:先排序,然后統計計算