Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查数组中的哪些元素相同_Java - Fatal编程技术网

Java 检查数组中的哪些元素相同

Java 检查数组中的哪些元素相同,java,Java,我试图检查数组中哪些元素是相同的,然后返回相同的元素。我想我必须在for循环中做一个for循环,但我不确定。这就是我到目前为止所做的: for (int p = 0 ; p < temperatures.length ; p++) { for (int j = 0 ; j < temperatures.length ; j++) { if (temperatures[p] == temperatures[j]) { System.out

我试图检查数组中哪些元素是相同的,然后返回相同的元素。我想我必须在for循环中做一个for循环,但我不确定。这就是我到目前为止所做的:

for (int p = 0 ; p < temperatures.length ; p++) {
    for (int j = 0 ; j < temperatures.length ; j++) {
        if (temperatures[p] == temperatures[j]) {
            System.out.println("matching" + j + p);
        }
    }
}
for(int p=0;p
我是如何创建阵列的:

for(int i = 0; i < temperatures.length; i++) {
    System.out.println("Please enter the temperature in Celcius for day " + (i+1));
    temperatures[i] = new Data(input.nextDouble());
}
for(int i=0;i
之所以说7次匹配是因为

for(int j = 0; j < temperatures.length; j++)
            {
                if(temperatures[p] == temperatures[j]) // This will have te..[0]==te..[0] .... te..[1]==te..[1] .... te..[6]==te..[6]
for(int j=0;j
你应该把它改成

for(int j = p+1; j < temperatures.length; j++)
            {
                if(temperatures[p] == temperatures[j]) //Here there's no chance of p==j. So this will work.
for(int j=p+1;j
另一种方法是首先对数组进行排序(只要它们是数字或可以排序),然后检查重复项就很简单了

使用
QuickSort
TimSort
进行排序是
O(n log n)
平均值,您可以在
O(n)
中分辨重复项。如果无法修改原始项,则需要在空间和时间上额外添加
O(n)

注意这是
O(n log n)

这个算法是
O(2n logn)
这是
O(n logn)=O(logn!)

带有随机整数的简单示例

        int[] d = ThreadLocalRandom.current().ints(100, 0, 100).toArray();
    Arrays.sort(d); // O(n log n)

    boolean dup = false;
    for (int i = 1; i < d.length; i++) { // O(n)
        if (d[i - 1] == d[i]) {
            dup = true;
        } else {
            if (dup) {
                System.out.print(d[i - 1] + " ");
            }
            dup = false;
        }
    }
    System.out.println("");

    for (int i = 0; i < d.length; i++) {
        System.out.print(d[i] + " ");
    }
int[]d=ThreadLocalRandom.current().ints(100,0100.toArray();
Arrays.sort(d);//O(n log n)
布尔dup=假;
对于(inti=1;i
您遇到的问题是什么?如果温度是双倍或浮动的,也许您应该使用一些三角形来相互比较这是一个家庭作业,或者类似的东西?如果不是,请参见问题。当我输入7个温度时,它说有7个匹配,因为我认为它将每个元素与其自身匹配。嘿,我认为您可以找到有用的ul这里给出的答案。我认为它非常接近您想要做的事情,并且解释得很好。问候和愉快的编码:)。URL:我按照您的建议做了,当我将所有温度都设置为相同温度时,我得到了0个匹配项?>我已将代码int j=I+1;更新为int j=p+1;因为p是您在第一个for循环中声明的变量,通过在Eclipse中运行此代码,我获得了正确的输出。