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.
题目描述:取出数组中出现一半以上的数
题目思路
思路1:数组中某个数x出现了一半以上,则在数组中删除两个不同的数,在剩下的数组中x仍然会出现一半以上
思路2:对数组进行排序,如果x在数组中出现了一半以上,那么取排序后中间的数,一定可以取到x
思路1代码:
class Solution {
public:
int majorityElement(vector<int> &num) {
int candicate=0;
int count=0;
for(int i=0;i<num.size();i++){
if(count==0){
candicate=num[i];
count++;
}else{
if(candicate!=num[i])
count--;
else count++;
}
}
return candicate;
}
};
思路2代码:
class Solution {
public:
int majorityElement(vector<int> &num) {
sort(num.begin(),num.end());
return num[num.size()/2];
}
};