-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22[课设].数组主元.cpp
143 lines (140 loc) · 2.42 KB
/
22[课设].数组主元.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include <stdio.h>
#include <time.h>
#include <malloc.h>
#include <memory.h>
#include <stdlib.h>
//线性遍历算法
int CountMainElement(int* nums, int n)
{
int element = nums[0], amount = 1;
for (int i = 1; i < n; i++)
{
if (amount == 0)
{
element = nums[i];
amount++;
continue;
}
if (nums[i] == element)
amount++;
else
amount--;
}
amount = 0;
for (int i = 0; i < n; i++)
{
if (nums[i] == element)
amount++;
}
if (amount > n / 2)
return element;
else
return -1;
}
//递归算法
//如果B C主元相同->A主元就是该主元
//如果B C没有主元->A没有主元
//如果B C主元不同->A主元只可能为其中之一
//如果B C只有一个主元->A主元只可能是它
int RecursionMainElement(int* nums, int begin, int end)
{
if (begin == end)
return nums[begin];
int half = (end - begin) / 2;
int left = RecursionMainElement(nums, begin, begin + half);
int right = RecursionMainElement(nums, begin + half + 1, end);
if (left == right)
return left;
if (left == -1 && right == -1)
return -1;
if (left == -1)
{
int amount = 0;
for (int i = begin; i <= end; i++)
if (nums[i] == right)
amount++;
if (amount > (end - begin + 1) / 2)
return right;
else
return -1;
}
if (right == -1)
{
int amount = 0;
for (int i = begin; i <= end; i++)
if (nums[i] == left)
amount++;
if (amount > (end - begin + 1) / 2)
return left;
else
return -1;
}
if (right != left)
{
int amountLeft = 0, amountRight = 0;
for (int i = begin; i <= end; i++)
{
if (nums[i] == right)
amountRight++;
if (nums[i] == left)
amountLeft++;
}
if (amountLeft > (end - begin + 1) / 2)
return left;
else if (amountRight > (end - begin + 1) / 2)
return right;
else
return -1;
}
}
int CompareCountMainElement(int* s, int n)
{
int element[500];
int nums[500];
memset(nums, 0, sizeof(int));
int NowP = 0;
int i = 0;
for (; i < n; i++)
{
int j = 0;
bool is_exist = false;
for (; j < NowP; j++)
{
if (element[j] == s[i])
{
is_exist = true;
nums[j] ++;
break;
}
}
if (!is_exist)
{
element[NowP] = s[i];
nums[NowP] = 1;
NowP++;
}
}
int MainElement = -1;
for (i = 0; i < NowP; i++)
{
if (nums[i] > n / 2)
{
MainElement = element[i];
break;
}
}
return MainElement;
}
int main()
{
int nums[100];
printf("Please input n:\n");
int n;
scanf_s("%d", &n);
int i;
for (i = 0; i < n; i++)
{
scanf_s("%d", nums + i);
}
printf("MainElement: %d", CountMainElement(nums, n));
}