zoukankan      html  css  js  c++  java
  • 力扣 | 169. 求众数

    题目:

    给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

    你可以假设数组是非空的,并且给定的数组总是存在众数。

    示例 1:

    输入: [3,2,3]
    输出: 3
    示例 2:

    输入: [2,2,1,1,1,2,2]
    输出: 2

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/majority-element

    思路:

    用栈来进行统计,空间复杂度:O(n) ,时间复杂度: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
    ",result);
    	return 0;
    }
    

      用栈来统计,空间复杂度O(1):

    cand存放结果数,count存放出现的次数

    #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
    ",result);
    	return 0;
    }
    

      

  • 相关阅读:
    51nod 1227 平均最小公倍数
    51nod 1238 最小公倍数之和 V3
    「G2016 SCOI2018 Round #2」B
    51nod 1258 序列求和 V4
    2301: [HAOI2011]Problem b
    POJ
    NOIP2017解题报告
    笔记-[ZJOI2014]力
    题解-Little C Loves 3 III
    李超线段树
  • 原文地址:https://www.cnblogs.com/chrysanthemum/p/11819413.html
Copyright © 2011-2022 走看看