数组中查找重复整数数字

在看剑指offer这本书的看到一种非常经典的解法,就是通过重头到尾重新排序这个数组每个数字,当扫描到数字m的时候判断下标为i的数字是否等于m如果是就寻找下一个,如果不是就判断下标为m的对应的数字是否等于m,如果它与第m个数字相等,就等于找到了一个重复的数字,如果不相等就把第i个数与第m个数交换位置,把m放在其对应的下标m的位置。例如数组{2,3,1,0,2,5,3}从下标为0的数开始找i=0对应的数字为2,不等于0,则就查找下标2所定应的数字为1不等于2,交换位置2就放在下标为2的位置上了,下标为0的数字变成1不等于0就去下标为1的位置查找1对应的数字为3不等于1就交换两者的位置,i=0我位置数字变成3,再去下标为3的位置查找i=3所对应的数字等于0所以与3交换,现在下标i=0所对应的数字是0,在进行i=1查询对应的数字为1,再往i=2数字去查看以此类推,查看到i=4是查看数字为2,在i=2的对应的数字为2找到第一个重复的数字。

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


#include"stdafx.h"
#include <iostream>
using namespace std;
int* findDuplicate(int number[], int length)
{
    int cout = 0;
if (number == NULL && length < 0)
{
return NULL;
}
for (int i = 0; i < length; i++)
{
if (number[i]<0 && number[i]>length - 1)
return NULL;
}
int repeat[10];
for (int i = 0; i < length; i++)
{
while (number[i] != i)
{
if (number[i] == number[number[i]])
{
repeat[cout++] = number[i];
}
int temp = number[i];
number[i] = number[temp];
number[temp] = temp;
}
}
return repeat;


};
int main()
{
int b[10] = { 2,3,1,0,2,5,3 };
int length = 7;
int *c;
c=findDuplicate(b, length);
for (int j = 0; j < 10; j++)
{
cout << c[j];
}


return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_35307209/article/details/80636459