topic:
Given an array of size n, the number of them find the congregation. The mode refers to the number of occurrences in the array is greater than ⌊ n / 2 ⌋ elements.
You can assume that the array is non-empty, and there is always a given array number of the congregation.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/majority-element
Ideas:
With a stack to statistics, the spatial complexity: O (n), the time complexity: O (n)
#include<stdlib.h>
#include<stdbool.h>
#include<stdio.h>
int majorityElement(int* nums,int numsSize )
{
int *stack =(int *)malloc(sizeof(int) * numsSize);
int top = -1;
int i;
for(i=0;i<numsSize;i++)
{
if(top==-1)
{
stack[++top]=nums[i];
}
else if(stack[top]==nums[i])
{
stack[++top]=nums[i];
}
else
{
top--;
}
}
return stack[0];
}
int main()
{
int nums[]={1,2,1,1,2,1,3,1};
int result = majorityElement(nums,7);
printf("result = %d\n",result);
return 0;
}
Stack to statistics, the space complexity O (1):
cand store the number of results, count the number of occurrences of the store
#include<stdlib.h>
#include<stdbool.h>
#include<stdio.h>
int majorityElement(int* nums,int numsSize )
{
int cand;
int count=0;
for(int i=0;i<numsSize;i++)
{
if(count==0)
{
cand = nums[i];
count++;
}
else if(cand==nums[i])
{
count++;
}
else
{
count--;
}
}
return cand;
}
int main()
{
int nums[]={1,2,1,1,2,1,3,1};
int result = majorityElement(nums,7);
printf("result = %d\n",result);
return 0;
}