有了上面的分析,代码不难写出: -
-
-
- #include <stdio.h>
- const int NO_REPEAT_FLAG = -1;
- void Swap(int &x, int &y)
- {
- int t = x;
- x = y;
- y = t;
- }
-
- int RadixSort(int a[], int n)
- {
- int i;
- for (i = 0; i < n; i++)
- {
- while (i != a[i])
- {
- if (a[i] == a[a[i]])
- return a[i];
- Swap(a[i], a[a[i]]);
- }
- }
- return NO_REPEAT_FLAG;
- }
- void PrintfArray(int a[], int n)
- {
- for (int i = 0; i < n; i++)
- printf("%d ", a[i]);
- putchar('\n');
- }
- int main()
- {
- printf(" 白话经典算法系列之十 一道有趣的GOOGLE面试题 \n");
- printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
-
- const int MAXN = 10;
- int a[MAXN] = {2, 4, 1, 5, 7, 6, 1, 9, 0, 2};
-
-
- printf("数组为: \n");
- PrintfArray(a, MAXN);
-
- int nRepeatNumber = RadixSort(a, MAXN);
- if (nRepeatNumber != NO_REPEAT_FLAG)
- printf("该数组有重复元素,此元素为%d\n", nRepeatNumber);
- else
- printf("该数组没有重复元素\n");
- return 0;
- }
运行结果如下图所示:

整个程序的核心代码只有短短5行左右,虽然有二重循环语句,但每个元素只会被访问一次,完成符合题目对时间复杂度的要求。 用基数排序来解决这道题目虽然思维巧妙,但会改动原数组的数据。有没有一种解法既找出一个重复的数据,又不改动数组中的数据了?请看《【白话经典算法系列之十一】一道有趣的GOOGLE面试题 --【解法2】》。 转载请标明出处,原文地址:http://blog.csdn.net/morewindows/article/details/8204460 欢迎关注微博:http://weibo.com/MoreWindows |