Most elements , link provided
method
![insert image description here](https://img-blog.csdnimg.cn/5881316ccf6f43daaca410686a3a06f3.png)
1. Moore vote
First, let’s briefly introduce Moore voting:
Moore voting is an algorithm used to solve the absolute majority problem.
What is the absolute mode?
In a set, if the number of occurrences of an element is more than the sum of the number of occurrences of all other elements, then it is said to be the absolute majority of the set. Equivalently, the absolute mode occurs more than half of the total number of elements.
Ideas:
Set up a counter
count
Use the absolute mode and the non-absolute mode to counter each other and cancel each other,
first traverse the array ,
encounter the samecount++
and different ones, set the current (voting object)count--
according to the count value, because the absolute mode > non-absolute mode, confront The remaining element must be the absolute modecandidate
Code:
int majorityElement(int* nums, int numsSize)
{
//moore
int i=0;
int candidate=nums[0];//设置投票对象
int count=1;//因为投票对象是nums[0],本身就是1票
for(i=1,count=1;i<numsSize;i++)//遍历数组
{
if(candidate==nums[i])
//当投票对象与当前元素相同时count++
count++;
else
{
//否则count--
count--;
if(count<0)
//当投票对象票数<0,重新选择对象
{
candidate=nums[i];
count=1;//票数重置为1
}
}
}
return candidate;
}
2. Reasonable but wrong approach
This is the error experienced by the subject owner , because it exceeds the running time , so it cannot be used
But note that the method in
2.2 will have different effects according to different methods of sorting . For example:
Bubble sort will time out of bounds, but quick sort will not
2.1 Cycle of Violence
When a horse stumbles, so does a cycle of violence
Ideas:
Set the counter
count=0
Use the outer loop variable as the array subscript, and
set a loop variable in the inner layer as the array subscript,
compare it with each array element, and if it is the same, when itcount++
is satisfiedcount>numssize/2
break
Code:
int majorityElement(int* nums, int numsSize)
{
int i = 0;
for (i = 0; i < numsSize; i++)
{
int count = 0;
for (int j = 0; j < numsSize; j++)
{
if (nums[i] == nums[j])
count++;
}
if (count > numsSize / 2)
break;
}
return nums[i];
}
2.2 Sorting + finding the middle element middle element
Ideas:
Sort first, then find nums[numsSize/2] (intermediate element), because the absolute majority must occupy more than half of the elements, so the intermediate element must be the absolute majority, and then return the intermediate element
Code:
int majorityElement(int* nums, int numsSize)
{
int i = 0;
int tmp = 0;
for (i = 0; i < numsSize - 1; i++)
{
for (int j = 0; j < numsSize - 1 - i; j++)
{
if (nums[j] > nums[j + 1])
{
tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
return nums[numsSize/2];
}
welcome to discuss