给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
给出数组[1,1,1,1,2,2,2],返回 1
思路:要求主元素的个数要大于总数的一半,那么我就把这些数从小到大排一遍,由主元素的定义,所给的数必定是单数,所以,我取数的一半是个小数,取其整形,必定在中位数的左边.................好像解释不了了,水过的吧........
再等一下,我又想起来了,因为主元素的个数必须多于一半,所以只要有主元素无论大小,排在前还是排在后,只要在中间有这个数,那么他就是主元素........终于绕过来了,哈哈哈
class Solution {
public:
/*
* @param nums: a list of integers
* @return: find a majority number
*/
int majorityNumber(vector<int> &nums) {
// write your code here
int ans=0;
int n=nums.size();
sort(nums.begin(),nums.end());
int w=nums[n/2];
return w;
}
};
笑死我了,我又看一遍,怎么想都过不了的才对,竟然给我过了,哈哈哈哈哈,等会再写一个更好的吧....
我又回来了。。。不知道对不对反正又过了...............................
class Solution {
public:
/*
* @param nums: a list of integers
* @return: find a majority number
*/
int majorityNumber(vector<int> &nums) {
// write your code here
int ans=0;
int n=nums.size();
int w=nums[0];
sort(nums.begin(),nums.end());
for(int i=0;i<n;i++)
{ if(w==nums[i])
{ans++;}
if(w!=nums[i])
{ w=nums[i];
ans=1;}
if(ans>n/2)
return w;
}
}
};
等等,还有一个
class Solution {
public:
/*
* @param nums: a list of integers
* @return: find a majority number
*/
int majorityNumber(vector<int> &nums) {
// write your code here
int ans= 0;
int w = 0;
for (int i = 0; i < nums.size(); i++)
{
if (ans == 0)
{
result = nums[i];
ans++;
}
else
{
if (result != nums[i])
{
ans--;
}
else
{
ans++;
}
}
} return w;
}
};