寻找数组支配者下标
2008-11-26 16:35
411 查看
一个数组,“支配者”是在数组中出现频率超过一半的整数, 例如[3,4,3,2,-1,3,3,3]数值“3”出现过5次,5除以8大于0.5
所以数值“3”是一个支配者; 而在这个数组中的支配者出现在数组下标[0,2,4,6,7]
写一个函数,在给定的整数数组中找出支配者所在的任意一个数组下标,如果一个数组中没有支配者返回-1;
要求:使用集合实现.
package Package;
import java.util.*;
/**
* @author atlightsgh@gmail.com
* 2008-11-26
*/
public class temp {
public static void main(String[] args) {
int[] array = { 1, 2, 7, 3, 3, 4, 4, 5, 6, 3, 2, 3, 3, 3, 3, 3, 3 };
System.out.println(FindMaster(array));
}
// 查找数组中的支配者,并返回其道次在数组中出的下标.算法复杂度O(n)
// 使用集合实现
static int FindMaster(int array[]) {
HashMap<Integer, Integer> counter = new HashMap<Integer, Integer>();
// 数组所有元素存入hashmap.并在存入时统计其个数
for (int e : array) {
Integer v = counter.get((Integer) e);
if (v == null)
counter.put(e, 1);
else
counter.put(e, v + 1);
}
Integer maxcounterK = 0;
Integer maxcounterV = 0;
// 寻找出现次数最多的元素和其出现次数
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
Integer entryV = entry.getValue();
if (maxcounterV < entryV) {
maxcounterV = entryV;
maxcounterK = entry.getKey();
}
}
// 查找支配者首次出现的下标
if (maxcounterV > array.length / 2)
for (int i = 0; i < array.length; i++)
if (array[i] == maxcounterK)
return i;
return -1;
}
}
所以数值“3”是一个支配者; 而在这个数组中的支配者出现在数组下标[0,2,4,6,7]
写一个函数,在给定的整数数组中找出支配者所在的任意一个数组下标,如果一个数组中没有支配者返回-1;
要求:使用集合实现.
package Package;
import java.util.*;
/**
* @author atlightsgh@gmail.com
* 2008-11-26
*/
public class temp {
public static void main(String[] args) {
int[] array = { 1, 2, 7, 3, 3, 4, 4, 5, 6, 3, 2, 3, 3, 3, 3, 3, 3 };
System.out.println(FindMaster(array));
}
// 查找数组中的支配者,并返回其道次在数组中出的下标.算法复杂度O(n)
// 使用集合实现
static int FindMaster(int array[]) {
HashMap<Integer, Integer> counter = new HashMap<Integer, Integer>();
// 数组所有元素存入hashmap.并在存入时统计其个数
for (int e : array) {
Integer v = counter.get((Integer) e);
if (v == null)
counter.put(e, 1);
else
counter.put(e, v + 1);
}
Integer maxcounterK = 0;
Integer maxcounterV = 0;
// 寻找出现次数最多的元素和其出现次数
for (Map.Entry<Integer, Integer> entry : counter.entrySet()) {
Integer entryV = entry.getValue();
if (maxcounterV < entryV) {
maxcounterV = entryV;
maxcounterK = entry.getKey();
}
}
// 查找支配者首次出现的下标
if (maxcounterV > array.length / 2)
for (int i = 0; i < array.length; i++)
if (array[i] == maxcounterK)
return i;
return -1;
}
}
相关文章推荐
- 一维静态数组_实例:寻找随机数最大值及其下标(附:源码)
- 寻找数组的下标索引值index方法
- 阿里13年研发笔试题 - 寻找有序数组中元素值等于其下标的所有元素
- leetcode——Search for a Range 排序数组中寻找目标下标范围(AC)
- 升序数组中寻找A[x] == x 的下标
- 寻找重复数字(数组作下标)
- 寻找升序整数数组中元素与对应下标相等的数
- Recursion 在数组中寻找神奇下标 @CareerCup
- 随机数组,从右往左寻找第一个大于当前数字的值得下标
- lintcode --寻找旋转排序数组中的最小值 II
- 删除指定下标的数组
- JavaScript求一个数组中重复出现次数最多的元素及其下标位置示例
- iOS中取数组内最大值最小值,下标,总和,平均值
- 数组下标为负数出现的问题(关于数组下标越界的检查)
- [PHP]使用array_merge重新排列数组下标
- 从两个有序数组的并集中寻找第k小元素
- 算法讨论(七)--已排序数组中寻找两个数,其和等于给定的数
- 编程之美——寻找数组中最大的K个数
- 用枚举类型作为数组下标
- 对一个数组,按照给定的下标进行排序,仅使用两两交换的方式