-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoreThanHalfNum.cpp
More file actions
100 lines (83 loc) · 1.86 KB
/
MoreThanHalfNum.cpp
File metadata and controls
100 lines (83 loc) · 1.86 KB
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
/*
* @filename: MoreThanHalfNum.cpp
* @author: Tanswer
* @date: 2018年02月25日 21:01:24
* @description:
*/
#include <iostream>
#include "Partition.h"
using namespace std;
bool g_bInputInvalid = false;
bool CheckMoreThanHalf(int* numbers, int length, int result)
{
int count = 0;
for(int i=0; i<length; i++)
{
if(numbers[i] == result)
count++;
}
bool isMoreThanHalf = true;
if(count*2 <= length)
{
isMoreThanHalf = false;
}
return isMoreThanHalf;
}
// 解法一 利用数组的特点
int MoreThanHalfNum_1(int* numbers, int length)
{
int result = numbers[0];
int times = 1;
for(int i=1; i<length; i++)
{
if(times == 0)
{
result = numbers[i];
times = 1;
}
else if(numbers[i] == result)
times++;
else
times--;
}
if(!CheckMoreThanHalf(numbers, length, result))
result = 0;
return result;
}
// 解法二
int MoreThanHalfNum_2(int* numbers, int length)
{
if(numbers == NULL || length <= 0)
{
g_bInputInvalid = true;
return 0;
}
int start = 0;
int end = length - 1;
int middle = length >> 1;
int index = Partition(numbers, length, start,end);
while(index != middle)
{
if(index > middle)
{
end = index - 1;
index = Partition(numbers, length, start, end);
}
else
{
start = index + 1;
index = Partition(numbers, length, start, end);
}
}
int result = numbers[middle];
if(!CheckMoreThanHalf(numbers, length, result))
result = 0;
return result;
}
int main()
{
int numbers[9] = {1,2,3,2,2,2,5,4,2};
cout << MoreThanHalfNum_1(numbers,9) << endl;
cout << MoreThanHalfNum_2(numbers,9) << endl;
return 0;
}