forked from jnozsc/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajority_Number.cpp
More file actions
33 lines (31 loc) · 786 Bytes
/
Copy pathMajority_Number.cpp
File metadata and controls
33 lines (31 loc) · 786 Bytes
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
/*
Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.
Example
for [1, 1, 1, 1, 2, 2, 2], return 1
*/
#include <vector>
using namespace std;
class Solution {
public:
/**
* @param nums: A list of integers
* @return: The majority number
*/
int majorityNumber(vector<int> nums) {
// write your code here
int majority = nums[0];
int count = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] == majority) {
count++;
} else {
count--;
}
if (count <= 0) {
majority = nums[i];
count = 1;
}
}
return majority;
}
};