LintCode_主元素
来源:互联网 发布:下载压缩解压软件 编辑:程序博客网 时间:2024/06/03 09:56
问题描述:
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
样例:给出数组[1,1,1,1,2,2,2],返回 1
挑战:要求时间复杂度为O(n),空间复杂度为O(1)
算法:
方法一:这种做法的缺点是,nums中有很大的数时,要求num[ ]数组的内存空间也要很大
public int majorityNumber(ArrayList<Integer> nums) { // write your code int [] num=new int[200]; int result=0; for(int i:nums){ num[i]++; } for(int j=0;j<num.length;j++){ if(num[j]>nums.size()/2){ result=j; break; } } return result; }
方法二:其实,这就是排序的另一种考察方式;我们可以先将nums排序,排序完后的数列中中间的数字肯定是出现次数大于nums长度的二分之一的数;
public int majorityNumber2(ArrayList<Integer> nums){ if(nums==null||nums.size()==0){ return 0; } int[] temp=new int[200]; temp[0]=nums.get(0); int pos=0; //插入排序 for(int i=1;i<nums.size();i++){ pos=i-1; while(pos>=0&&nums.get(i)>temp[pos]){ temp[pos+1]=temp[pos]; pos--; } temp[pos+1]=nums.get(i); } return temp[nums.size()/2]; }
0 0
- LintCode_主元素
- LintCode_第k大元素
- LintCode_数组剔除元素后的乘积
- LintCode_中位数
- LintCode_不同的路径
- lintCode_二分查找
- LintCode_子数组之和
- LintCode_合并区间
- LintCode_有效回文串
- LintCode_尾部的零
- LintCode_字符串查找
- LintCode_最小差
- LintCode_颜色分类
- lintcode_单词切分
- lintcode_快乐数
- lintcode_整数排序 II
- LintCode_单词接龙
- LintCode_安排课程
- 《opencv3编程入门》之一:图像处理、计算机视觉与opencv
- 浅谈 malloc/free 和 new/delete
- 小米开源文件管理器MiCodeFileExplorer-源码研究(6)-媒体文件MediaFile和文件类型MimeUtils
- boost::bind
- android studio 更改背景和设置字体大小
- LintCode_主元素
- 系统安装相关:U盘刻录(用U盘装ubuntu简要方法)
- OC第一节--OC的基本
- 最短路径基础
- hihocoder 1142 : 三分·三分求极值
- 关于apache tomcat的几个版本
- const ||c
- Java堆栈详解
- IOS--导航栏