我尝试了不同的方法来获取用户的输入序列,但不知道该怎么做。这是我的代码。 大小为N的数组A中的多数元素是出现超过N / 2次的元素。例如(3,3,4,2,4,4,2,4,4)有多数元素(4),而数组(3,3,4,2,4,4,2,4)有多数元素(4)没有多数元素。我正在尝试从用户那里获得一系列输入。
import java.util.Scanner;
class rough1 {
public static int arrMajority1( int A[] ) {
int n = A.length;
for( int i = 0; i < A.length; i++ ) {
int c = 1;
for( int j = i + 1; j < A.length; j++ )
if( A[ i ] == A[ j ] )
c = c + 1;
if( c > ( A.length / 2 )) {
return A[ i ];
}
}
return -1;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int A[] = new int [];
A[] = input.nextInt();
String employee = "A[]";
String delims = "[,]";
String[] tokens = employee.split(delims);
if (arrMajority1(A) != -1)
System.out.println("The majority element is " + arrMajority1(A));
else
System.out.println("There is no majority element.");
}
}
答案 0 :(得分:1)
这个怎么样?
public static void main(String[] args) throws FileNotFoundException {
int[] arrayWithMajorityElements = {3,3,4,2,4,4,2,4,4};
Integer[] majorityElements = getMajorityElements(arrayWithMajorityElements);
System.out.println(Arrays.toString(majorityElements));
// result = 4
int[] arrayWithoutMajorityElements = {3,3,4,2,4,4,2,4};
majorityElements = getMajorityElements(arrayWithoutMajorityElements);
System.out.println(Arrays.toString(majorityElements));
// result = empty array (ie no majory elements)
}
private static Integer[] getMajorityElements(int[] array) {
Map<Integer, Integer> map = new HashMap<>();
for (int i : array) {
int count = 0;
if (map.containsKey(i)) {
count = map.get(i);
}
map.put(i, ++count);
}
List<Integer> majorityElements = new ArrayList<>();
int check = array.length / 2;
for (Integer i : map.keySet()) {
if (map.get(i) > check) {
majorityElements.add(i);
}
}
return majorityElements.toArray(new Integer[majorityElements.size()]);
}
请注意,我假设您可以拥有多个多数元素 - 如果您不能,那么您必须修改最后一个循环