gpt4 book ai didi

java - 查找数组中出现的重复项数 - Java

转载 作者:行者123 更新时间:2023-11-30 06:43:46 37 4
gpt4 key购买 nike

我无法解决这个问题。需要找到重复项,我做到了。现在剩下的就是打印重复出现在数组中的次数。我刚开始使用 Java,所以这需要硬编码才能让我理解。花了最后两天试图弄清楚但没有运气..任何帮助都会很棒!话不多说,这里是代码..

import java.util.Arrays;
public class LoopTest {

public static void main(String[] args) {

int[] array = {12,23,-22,0,43,545,-4,-55,43,12,0,-999,-87};
int positive_counter = 0;
int negative_counter = 0;


for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_counter++;
} else if(array[i] < 0) {
negative_counter++;
}
}

int[] positive_array = new int[positive_counter];
int[] negative_array = new int[negative_counter];

positive_counter = 0;
negative_counter = 0;

for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_array[positive_counter++] = array[i];
} else if(array[i] < 0) {
negative_array[negative_counter++] = array[i];
}
}

System.out.println("Positive array: " + (Arrays.toString(positive_array)));
System.out.println("Negative array: " + (Arrays.toString(negative_array)));

Arrays.sort(array);
System.out.println("Array duplicates: ");
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if(array[i] == array[j]) {
System.out.println(array[j]);
}

}
}
}
}

最佳答案

由于您已经对数组进行了排序,因此您只需一个循环即可找到重复项(它们将彼此相邻,对吗?)。所以你可以这样做:

            Arrays.sort(array);
System.out.println("Array duplicates: ");
int lastValueCount=1; //How many times we met the current value (at least 1 - this time)
for (int i = 1; i < array.length; i++){
if(array[i] == array[i-1])
lastValueCount++; //If it is the same as the previous increase the count
else {
if(lastValueCount>1) //If it is duplicate print it
System.out.println(array[i-1]+" was found "+lastValueCount+" times");
lastValueCount=1; //reset the counter
}
}

你的数组的结果是:

Array duplicates: 
0 was found 2 times
12 was found 2 times
43 was found 2 times

您也可以使用一些 Java 花里胡哨的东西,比如将值插入 Map 或类似的东西,但我猜您是从算法的角度来看的,所以上面是一个简单的答案,只有一个循环

关于java - 查找数组中出现的重复项数 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51652434/

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