判断数组是否有重复数字

    给定一个长度为N的数组,其中每个元素的取值范围都是1到N。判断数组中是否有重复的数字。(原数组不必保留)

分析:因为数组中的每一个元素的范围已经确定,我们可以通过将各个元素交换到下标与其相等的位置上去看会不会发生冲突来判断是否存在重复的数字。

 1 #include "stdafx.h"
 2 #include <assert.h>
 3 
 4 void SwapValue (int *NumA, int *NumB)
 5 {
 6     assert (NULL != NumA);
 7 
 8     assert (NULL != NumB);
 9 
10     if ((*NumA) != (*NumB))
11     {
12         *NumA ^= *NumB;
13         *NumB ^= *NumA;
14         *NumA ^= *NumB;
15     }
16 }
17 bool RepeatNumber(int *a, int N)
18 {
19     assert (NULL != a);
20 
21     assert (N > 0);
22 
23     for (int i = 0; i < N; ++i)
24     {
25         if (i != a[i])
26         {
27             while (a[i] != a[a[i]])
28             {
29                 SwapValue (&a[i], &a[a[i]]);
30             }
31             else
32             {
33                 return (true);
34             }
35         }
36     }
37 
38     return (false);
39 }
40 
41 int main(void)
42 {
43     int a[100];
44     int N;
45 
46     scanf ("%d", &N);
47     for (int i = 0; i < N; ++i)
48     {
49         scanf ("%d", &a[i]);
50     }
51 
52     if (RepeatNumber (a, N))
53     {
54         printf ("Yes, there are duplicate numbers!\n");
55     }
56     else
57     {
58         printf ("No, there is no duplicate numbers!\n");
59     }
60 
61     return (0);
62 }

原文地址:https://www.cnblogs.com/ldjhust/p/3003546.html