华为机试练习---找出数组中的"支配者"
2014-08-31 16:46
218 查看
package interview; import java.util.Arrays; import java.util.Scanner; /** * 找出一个数组中的"支配者":即出现频率超过一半的数 * @author USER * */ public class FindDominator { public static void main(String[] args) { Scanner in = new Scanner(System.in); String string = in.nextLine(); String[] s = string.split(" "); int[] a = new int[s.length]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(s[i]); } int m = dominator(a); if (m == -1) { System.out.println("no dominator"); }else { System.out.println("the dominator is:"+m); } } private static int dominator(int[] a) { // TODO Auto-generated method stub Arrays.sort(a);//对数组排序,是升序,便于查找相同的数.注意Arrays.sort()排序是按字符的ASCII码值排序的 int count = 1; for (int i = 0; i < a.length-1; i++) { if (a[i] == a[i+1]) { count++; if ((double)count / a.length > 0.5) { return a[i]; } }else { count = 1; } } return -1; } }
相关文章推荐
- "数组引用"以避免"数组降阶"(c++)
- 华为跨国营销的"中国功夫"
- 华为机试——找出数组中不同的两个数
- SQL Server存储过程中使用"数组参数"
- 华为机试——找出数组中不同的数字
- js 用"name"做数组变量命名的问题
- 有一个字符数组的内容为:"student a am i",请你将数组的内容改为"i am a student"
- "找出字符串中第一个不重复的字符"和"找出字符串中最后一个重复的字符"的两种方法的C++实现
- 华为机试——找出一个数组中满足2^n的元素个数
- 在DP中使用"滚动数组"
- 华为机试题---判断一个字符串中的"( )"是否配对
- 一个关于"int型二维数组"及"指针数组"作函参的地址传递和带回返回值的问题,指针的拓展练习〈二〉
- "数组引用"以避免"数组降阶"(c++)
- 有一个字符数组的内容为:"student a am i",请你将数组的内容改为"i am a student".
- "cout<<char数组名/数组指针"跟"cout<<int数组/数组指针"的差别
- VC|MFC内存不能为"read"+仅通过崩溃地址找出源代码的出错行
- 数组名取地址所算数运算应注意的"trap"
- 将数组"student a am i"改为"i am a student".
- Objective-C 数组一 "不可变数组"
- PHP数组的"自然链接"