gpt4 book ai didi

java - 计算整数数组中的重复元素

转载 作者:搜寻专家 更新时间:2023-11-01 04:04:28 24 4
gpt4 key购买 nike

我有一个整数数组crr_array,我想对重复出现的元素进行计数。首先,我读取数组的大小并使用从控制台读取的数字对其进行初始化。在数组 new_array 中,我存储了重复的元素。数组 times 存储元素连续出现的次数。然后,我尝试搜索重复序列并以特定格式打印它们。但是,它不起作用。

// Get integer array size
Scanner input = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = input.nextInt();

int[] crr_array = new int[size];
int[] new_array= new int[size];
int[] times = new int[size];

// Read integers from the console
System.out.println("Enter array elements: ");
for (int i = 0; i < crr_array.length; i++) {
crr_array[i] = input.nextInt();
times[i] = 1;
}

// Search for repeated elements
for (int j = 0; j < crr_array.length; j++) {
for (int i = j; i < crr_array.length; i++) {
if (crr_array[j] == crr_array[i] && j != i) {
new_array[i] = crr_array[i];
times[i]++;
}
}
}



//Printing output
for (int i = 0; i < new_array.length; i++) {
System.out.println("\t" + crr_array[i] + "\t" + new_array[i] + "\t" + times[i]);

}

我希望输出看起来像这样:

There are <count_of_repeated_element_sequences> repeated numbers 
<repeated_element>: <count> times
...

例如:

There are 3 repeated numbers:
22: 2 times
4: 3 times
1: 2 times

如何找到重复元素及其计数?如何打印它们如上所示?

最佳答案

这类问题可以通过字典(Java中的HashMap)轻松解决。

  // The solution itself 
HashMap<Integer, Integer> repetitions = new HashMap<Integer, Integer>();

for (int i = 0; i < crr_array.length; ++i) {
int item = crr_array[i];

if (repetitions.containsKey(item))
repetitions.put(item, repetitions.get(item) + 1);
else
repetitions.put(item, 1);
}

// Now let's print the repetitions out
StringBuilder sb = new StringBuilder();

int overAllCount = 0;

for (Map.Entry<Integer, Integer> e : repetitions.entrySet()) {
if (e.getValue() > 1) {
overAllCount += 1;

sb.append("\n");
sb.append(e.getKey());
sb.append(": ");
sb.append(e.getValue());
sb.append(" times");
}
}

if (overAllCount > 0) {
sb.insert(0, " repeated numbers:");
sb.insert(0, overAllCount);
sb.insert(0, "There are ");
}

System.out.print(sb.toString());

关于java - 计算整数数组中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17630727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com