LeetCode 169

本文介绍了一个简单的C语言程序,用于解决LeetCode上的多数元素问题。该问题要求在给定数组中找到出现次数超过一半的元素。文章提供的解决方案利用了Boyer-Moore投票算法,通过迭代数组并维护当前候选者及其计数来实现。最后通过一个示例数组{3,2,3}

Majority Element

Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

 

 1 /*************************************************************************
 2     > File Name: LeetCode169.c
 3     > Author: Juntaran
 4     > Mail: Jacinthmail@gmail.com
 5     > Created Time: Tue 10 May 2016 02:40:25 PM CST
 6  ************************************************************************/
 7  
 8 /*************************************************************************
 9 
10     Majority Element
11     
12     Given an array of size n, find the majority element. 
13     The majority element is the element that appears more than ⌊ n/2 ⌋ times.
14 
15     You may assume that the array is non-empty and the majority element always exist in the array.
16 
17  ************************************************************************/
18 
19 #include<stdio.h>
20 
21 int majorityElement( int* nums, int numsSize )
22 {
23     int ret = nums[0];
24     int count = 1;
25     
26     int i;
27     for( i=1; i<numsSize; i++ )
28     {
29         if( ret == nums[i] )
30         {
31             count ++;
32         }
33         else
34         {
35             count --;
36         }
37         if( count == 0 )
38         {
39             ret = nums[i];
40             count ++;
41         }
42     }
43     return ret;
44 }
45 
46 int main()
47 {
48     int nums[] = {3,2,3};
49     int numsSize = 3;
50 
51     int ret = majorityElement( nums, numsSize );
52     printf("%d\n", ret);
53 
54     return 0;
55 }

 

转载于:https://www.cnblogs.com/Juntaran/p/5479091.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值