-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path数组中个数超过一半的数(包含不存在的情况).txt
49 lines (46 loc) · 1.16 KB
/
数组中个数超过一半的数(包含不存在的情况).txt
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
class Solution {
public:
/*int MoreThanHalfNum_Solution(vector<int> numbers) {//抵消计数法,然后统计current的个数
int countnum = 0;
int current = 0;
for(int i=0;i<numbers.size();++i)
{
if(countnum == 0)
{
current=numbers[i];
countnum++;
}
else
{
if(current!=numbers[i])countnum--;
else
countnum++;
}
}
countnum = 0;
for(int i=0;i<numbers.size();++i)
{
if(current==numbers[i])
countnum++;
}
if(countnum>(numbers.size()/2))
{
return current;
}
else
{
return 0;
}
}*/
int MoreThanHalfNum_Solution(vector<int> numbers) {//利用map保存一下个数即可
map<int,int> hash;
for(int i=0;i<numbers.size();++i)
hash[numbers[i]]++;
for(int i=0;i<numbers.size();++i)
{
if(hash[numbers[i]]>(numbers.size()/2))
return numbers[i];
}
return 0;
}
};