我有一个整数数组,并且有一个或多个元素具有相同的整数值。我想确定其他整数中的多数整数值。这是如何实现的。
问问题
1096 次
3 回答
2
我不确定您是否正在寻找“最佳”解决方案,但是下面的代码有效。
方法:
public static Integer majority(int[] array) {
Map<Integer, Integer> count = new HashMap<Integer, Integer>();
for (int number : array) {
if (count.containsKey(number)) {
count.put(number, count.get(number) + 1);
} else {
count.put(number, 1);
}
}
Integer majority = null;
Integer majorityCount = null;
for (Integer key : count.keySet()) {
if (count.get(key) > array.length / 2) {
majority = key;
majorityCount = count.get(key);
}
}
return majority;
}
这是测试运行器:
public static void main(String[] args) {
int[] array = {0, 1, 3, 4, 2, 1, 0, 0, 0, 10, 10, 0, 0};
int[] array1 = {0, 1, 3, 4, 2, 1, 0, 0, 0, 0, 0};
System.out.println(majority(array));
System.out.println(majority(array1));
}
和输出
null
0
我希望这就是你要找的。
于 2013-02-21T16:27:49.460 回答
1
下面的代码将告诉您多数整数是什么以及它在数组中出现的次数。显然我没有考虑优化解决方案,因为它没有被问到。
int array[] = new int[10];
array[0] = 0;
array[1] = 9;
array[2] = 1;
array[3] = 2;
array[4] = 3;
array[5] = 6;
array[6] = 7;
array[7] = 8;
array[8] = 5;
array[9] = 4;
HashMap map = new HashMap();
int majorInt = 0;
int maxCounter = 0;
boolean majorIntFound = false;
for (int i = 0; i < array.length; i++) {
Integer counter = (Integer) map.get(array[i]);
if (counter != null) {
majorIntFound = true;
int counterInt = counter.intValue();
map.put(array[i], ++counterInt);
if (counterInt > maxCounter) {
maxCounter = counterInt;
majorInt = array[i];
}
} else {
map.put(array[i], new Integer(1));
}
}
if (majorIntFound)
System.out.println(" Majority int is: " + majorInt + " counter: " + maxCounter);
else
System.out.println("No majority Int");
于 2013-02-21T16:43:40.767 回答
0
我想你想要这样的东西?
import java.util.Random;
public class Majority{
public static void main(String [] args){
int [] random = new int[100];
Random r = new Random();
for (int i : random){
int j = r.nextInt(21);
random[i] = j;
}
int majority = 0, currentCount = 0, highestCount = 0;
for (int i : random){
for (int j : random){
if(random[i] == random[j])
currentCount++;
}
if(currentCount > highestCount){
majority = random[i];
highestCount = currentCount;
}
}
System.out.print("The majority number is: " + majority);
}
}
于 2013-02-21T16:48:42.983 回答