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.
思路:
因为出现次数最多的数的数量比其他所有数的个数的和还多,所以遇见不同的两个数就丢弃。最后还能剩下来的就是数量最多的那个。
代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int res, num = 0;
for (int i = 0; i < nums.size(); i++){
if(!num){
res = nums[i];
num = 1;
} else if (res == nums[i]){
num++;
} else {
num--;
}
} return res;
}
};
Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
思路:
代码:
这里写代码片