来源:Leetcode
原帖:https://leetcode.com/problems/majority-element/
题目:
Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example, For [1, 1, 1, 1, 2, 2, 2], return 1.
代码:
原帖:https://leetcode.com/problems/majority-element/
题目:
Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example, For [1, 1, 1, 1, 2, 2, 2], return 1.
代码:
class Solution {
public:
int majorityElement(vector<int> &num) {
int candidate = 0, count = 0;
for (int i = 0; i < num.size(); ++i) {
if (count == 0) {
candidate = num[i];
count++;
} else if (candidate == num[i]) {
count++;
} else {
count--;
}
}
return candidate;
}
};
No comments:
Post a Comment