寻找多数元素
2015-08-01 16:39
232 查看
多数元素是指在数组中出现次数大于等于数组数目一半的元素,我们的算法首先得出这样一个候选元素,然后一遍扫描数组,查看是否是多数元素。
/** * * @author pc *找出数组中最多的那个元素 *两种方法分为递归版与非递归版 */ public class MAJORITY { public static int majority(int a[]){ int count=1; int k=0; //用来指向元素的下标 int c=a[0];//用来返回最多的那个元素 for(int j=1;j<a.length;j++){ if (count==0){ k=j; c=a[j]; count++; } if(a[j]==c) count++; else count--; } count=0; for(int i=0;i<a.length;i++){ if(a[i]==c) count++; } if(count>=a.length/2){ return c; } else{ return -1; } } public static void main(String args[]){ int[] a={3,4,5,6,1,7,3,3,3,3}; System.out.println(majority(a)); } }
相关文章推荐
- pthread 线程库编程 一:线程与互斥锁 mutex_lock
- 判断文件编码
- ListView回收机制相关分析
- 机房收费系统之组合查询
- 小贝_redis web管理界面工具安装
- Amazon AWS S3 for PHP 的API使用测试
- C语言编程入门——程序练习(上)
- 刚开始学:C语言 swap算法
- 我眼中的软件项目实施(转)
- 性能测试脚本开发(LR.NET控件)
- LeetCode—数组(2)
- app后端设计(4)-- 通讯的安全性
- hdoj 5112 A Curious Matt 【签到题】
- IOS 7 自动布局详解(一)
- hadoop参数配置详解
- 【排序】希尔排序模板
- ubuntu 14.04 无线网卡驱动安装
- maven的本地仓库 repository
- resin JVM内存设置简要
- onCreate()过程中获取View的width和Height