Force button: 169. Most elements

Insert picture description here
Idea:
The simplest idea is hush's addressing method to count the number of each number. Finally traverse the hush output with the largest number.
This is obviously very space consuming. Because the question does not specify the value range of the size of each number.
So let's change another method: use the stack to solve the problem.
For example:
Insert picture description here
from the above figure, we can draw the following three conclusions:

  • Stack is empty
  • The top element of the stack and the element are equal to the stack
  • Stack fixed and elements are not equal to pop out of the stack

In practical and easy-to-understand terms, it is different offsets one by one. Then the ones left are the most numerous.

Note:
There is a condition in the question that the number of most elements is greater than 1/2 of the array. It is precisely because of this that this method can be used.
If it is not then the method cannot be used.
For example: 2 2 1 3 5 The last thing left is 5. This is obviously incorrect.
code show as below:

int majorityElement(int* nums, int numsSize){
    
    
    int *stack=(int *)malloc(sizeof(int)*numsSize);
    int top=-1;
    for(int i=0;i<numsSize;i++)
    {
    
    
    	if(top==-1)//栈里没有元素,入栈
    	{
    
    
    		stack[++top]=nums[i];
    		continue;
    	}
    	if(nums[i]==stack[top])//相等入栈
    	{
    
    
    		stack[++top]=nums[i];
    		continue;
    	}
    	top--;//不相等,出栈
    }
    return stack[0];
}

The time complexity at this time is O(n), and the space complexity is also O(n).
In fact, through analysis, you will find that the stack is actually not that big. We can use one element to count the top element of the stack, and
one element to count the number.
code show as below:

int majorityElement(int* nums, int numsSize){
    
    
    int count=0;
    int number=0;
    for(int i=0;i<numsSize;i++)
    {
    
    
    	if(count==0)//栈为空入栈
    	{
    
    
    		number=nums[i];
    		count++;
    		continue;
    	}
    	else if(number==nums[i])
    	{
    
    
    		count++;
    	}
    	else//出栈
    		count--;
    }
    return number;
}

The time complexity of the above method is O(n), and the space complexity is O(0).

The above summary is based on this video:
https://www.bilibili.com/video/BV13s41197my

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/115026322