-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfindNumOneFourth.cpp
More file actions
72 lines (62 loc) · 1.38 KB
/
findNumOneFourth.cpp
File metadata and controls
72 lines (62 loc) · 1.38 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
#include <iostream>
#include <vector>
using namespace std;
// 在有序数组中找出出现次数超过总长度1/4的一个数
int findFirstOccur(vector<int>& nums, int target){
int start = 0, end = nums.size() - 1;
while(start + 1 < end){
int mid = start + (end - start) / 2;
if(nums[mid] >= target){
end = mid;
}
else if(nums[mid] < target){
start = mid;
}
}
int first = -1;
if(nums[start] == target){
first = start;
}
else if(nums[end] == target){
first = end;
}
return first;
}
int findLastOccur(vector<int>& nums, int target){
int start = 0, end = nums.size() - 1;
while(start + 1 < end){
int mid = start + (end - start) / 2;
if(nums[mid] <= target){
start = mid;
}
else if(nums[mid] > target){
end = mid;
}
}
int last = -1;
if(nums[end] == target){
last = end;
}
else if(nums[start] == target){
last = start;
}
return last;
}
int findNumOneFourth(vector<int> &nums){
int n = nums.size();
// the number that occurs frequecy > 1 / 4 out of all MUST be at position 1/4, 1/2 or 3/4
for(int pos = n/4 - 1; pos < n; pos += n/4){
int target = nums[pos];
int first = findFirstOccur(nums, target);
int last = findLastOccur(nums, target);
if(last - first + 1 > n/4){
return target;
}
}
return -1;
}
int main(void){
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8};
cout<<findNumOneFourth(nums) << endl;
return 0;
}