// 找出数组中重复出现的元素.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
/*
for i := 0 to n - 1
while A[A[i]] != A[i]
swap(A[i], A[A[i]])
end while
end for
for i := 0 to n - 1
if A[i] != i then
print A[i]
end if
end for
*/
void swap(int A[], int i, int j)
{
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
void resortArray(int A[], int len)
{
/*
A[A[idx]] == A[idx]有两种可能:
1) A[idx] == idx --> A[0] == 0; A[1] == 1; A[2] == 2; A[3] == 3...
2) 以A[idx]的值作为坐标的值和A[idx]相同, 如A[A[3]] == A[3](A[3]这个值是错的,譬如A[3] = 4,因此有A[A[3]] == A[3] -> A[4] == A[3] == 4
整个思想是 A[idx]的值 要 == idx
*/
for (int idx = 0; idx < len; idx++)
{
while(A[A[idx]] != A[idx])
swap(A, idx, A[idx]);
}
for (int i = 0; i < len; i++)
{
if (A[i] != i)
printf("%d ", A[i]);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int ARR[] = {1, 2, 3, 1, 3, 0, 6};
int len = sizeof(ARR)/sizeof(ARR[0]);
resortArray(ARR, len);
return 0;
}
找出数组中所有重复的数
最新推荐文章于 2019-08-31 18:13:35 发布