1 #include<iostream>
2 using namespace std;
3
4 int Frepeat(int num[],int length)
5 {
6 if(num == nullptr && length <1)
7 {
8 return -1;
9 }
10
11 for(int i =0 ;i <length ;i++)
12 {
13 if(num[i] < 0 || num[i]>= length)
14 return -1;
15 }
16 //int n[] = new int[length -1]();// 这里显示类型不匹配 cannot convert from int * to int []
17
18 int *n = new int[length -1]();
19
20 for(int i = 0 ;i < length ;i++)
21 {
22 int d = num[i];
23 n[d]++;
24 if(n[d] > 1)
25 {
26 return d;
27 }
28 }
29 return -1;
30 }
31
32 int main()
33 {
34 int a[] = {2,0,1,3,4,5,6};
35 int result = Frepeat(a,7);
36 cout << result;
37 system("pause");
38 }
- new数组的写法是
而
只申请了一个对象,并且把初值设成了n...
- new申请的空间是返回一个指针
- int n[] ,这样的数组只有在函数的函数中才能指针化数组,其他的情况下,都不是指针。
1 int Frepeat02(int num[],int length) //改变原始数组的位置
2 {
3 if(num == nullptr && length <1)
4 {
5 return -1;
6 }
7
8 for(int i =0 ;i <length ;i++)
9 {
10 if(num[i] < 0 || num[i]>= length)
11 return -1;
12 }
13
14 for(int i = 0;i <length; i++)
15 {
16 while(num[i] != i)
17 {
18 if(num[ num[i] ] == num[i]) //这里就是交换的两个下标的值相等
19 {
20 return num[i];
21
22 }
23
24 //int temp = num[i]; 这里并没有交换啊 陷入死循环的
25 //num[i] = num[ num[i] ];
26 //num[ num[i] ] = temp;
27
28 int temp = num[i];
29 num[i] = num[ temp ];
30 num[ temp ] = temp;
31 }
32 }
33 return -1;
34 }
1 int Fcount(int *num,int length ,int Start, int mid)
2 {
3 if(num == nullptr && Start <0 && mid <Start)
4 {
5 return -1;
6 }
7 int count = 0;
8 for(int i = 0 ;i< length ;i++)
9 {
10 if(num[i] >= Start && num[i]<= mid)
11 count++;
12 }
13 return count;
14 }
15
16 int Frepeat_nochange(int num[],int length) //不改变原始数组的位置 采用的是二分查找方法
17 {
18 if(num == nullptr && length <= 1)
19 {
20 return -1;
21 }
22
23 for(int i = 0 ;i <length ;i++)
24 {
25 if(num[i] < 0 || num[i]>= length)
26 return -1;
27 }
28 int Start = 0;
29 int End = length - 1;
30 while(Start <= End)
31 {
32 int mid = (End - Start)/2 + Start;
33 int count = Fcount(num,length,Start,mid);
34 if(Start == End )
35 {
36 if(count >1)
37 return Start;
38 else
39 return -1;
40 }
41 if(count > mid -Start +1)
42 End = mid;
43 else
44 Start = mid +1 ;
45
46 }
47 return -1;
48
49 }