您的位置:首页 > 其它

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3

2016-10-08 14:43 931 查看
// 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;
}

思路:先排序,然后统计计算
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐