【白话经典算法系列之十六】“基数排序”之数组中缺失的数字

from:【白话经典算法系列之十六】“基数排序”之数组中缺失的数字

本文地址:http://blog.csdn.net/morewindows/article/details/12683723 转载请标明出处,谢谢。

欢迎关注微博:http://weibo.com/MoreWindows    

首先看看题目要求:

给定一个无序的整数数组,怎么找到第一个大于0,并且不在此数组的整数。比如[1,2,0]返回3[3,4,-1,1]返回2[1, 5, 3, 4, 2]返回6[100, 3, 2, 1, 6,8, 5]返回4。要求使用O(1)空间和O(n)时间。



这道题目初看没有太好的思路,但是借鉴下《白话经典算法系列之十  一道有趣的GOOGLE面试题》这篇文章,我们不发现使用“基数排序”正好可以用来解决这道题目。

{1, 3, 6, -100, 2}为例来简介这种解法:

从第一个数字开始,由于a[0]=1,所以不用处理了。

第二个数字为3,因此放到第3个位置(下标为2),交换a[1]a[2],得到数组为{1, 6, 3, -100, 2}。由于6无法放入数组,所以直接跳过。

第三个数字是3,不用处理。

第四个数字是-100,也无法放入数组,直接跳过。

第五个数字是2,因此放到第2个位置(下标为1),交换a[4]a[1],得到数组为{1, 2, 3, -100, 6},由于6无法放入数组,所以直接跳过。
此时“基数排序”就完成了,然后再从遍历数组,如果对于某个位置上没该数,就说明数组缺失了该数字。如{1, 2, 3, -100, 6}缺失的就为4


这样,通过第i个位置上就放i的“基数排序”就顺利的搞定此题了。



代码也非常好写,不过在交换两数时要注意判断下两个数字是否相等,不然对于像{1, 1, 1}这样的数据会出现死循环。

完整的代码如下:
  1. // 【白话经典算法系列之十六】“基数排序”之数组中缺失的数字

  2. //  by MoreWindows( http://blog.csdn.net/MoreWindows ) 

  3. //  欢迎关注http://weibo.com/morewindows

  4. #include <stdio.h>

  5. void Swap(int &a, int &b)

  6. {

  7.   int c = a;

  8.   a = b;

  9.   b = c;

  10. }

  11. int FindFirstNumberNotExistenceInArray(int a[], int n)

  12. {

  13.   int i;

  14.   // 类似基数排序,当a[i]>0且a[i]<N时保证a[i] == i + 1

  15.   for (i = 0; i < n; i++)

  16.     while (a[i] > 0 && a[i] <= n && a[i] != i + 1 && a[i] != a[a[i] - 1])

  17.         Swap(a[i], a[a[i] - 1]);

  18.   // 查看缺少哪个数

  19.   for (i = 0; i < n; i++)

  20.     if (a[i] != i + 1)

  21.       break;

  22.   return i + 1;

  23. }

  24. void PrintfArray(int a[], int n)

  25. {

  26.   for (int i = 0; i < n; i++)

  27.     printf("%d ", a[i]);

  28.   putchar('\n');

  29. }

  30. int main()

  31. {

  32.   printf("    【白话经典算法系列之十六】“基数排序”之数组中缺失的数字\n");

  33.   printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n");

  34.   printf(" -- http://blog.csdn.net/morewindows/article/details/12683723 -- \n\n");


  35.   const int MAXN = 5;

  36.   //int a[MAXN] = {1, 2, 3, 4, 7}; 

  37.   //int a[MAXN] = {1, 3, 5, 4, 2};

  38.   int a[MAXN] = {2, -100, 4, 1, 70};

  39.   //int a[MAXN] = {2, 2, 2, 2, 1};

  40.   PrintfArray(a, MAXN);

  41.   printf("该数组缺失的数字为%d\n", FindFirstNumberNotExistenceInArray(a, MAXN));

  42.   return 0;

  43. }


运行结果如下图所示:

 


本文地址:http://blog.csdn.net/morewindows/article/details/12683723 转载请标明出处,谢谢。

欢迎关注微博:http://weibo.com/MoreWindows