【问题标题】:I want to check a number in array我想检查数组中的数字
【发布时间】:2022-12-18 18:32:00
【问题描述】:

我想检查一个无序数组中的数字,如果该数字不包含在数组中我想打印它,如果它包含我不想打印它, 当我尝试我的代码时,我认为我可以将数组与有序数组进行比较,但它打印的是包含的数字而不是未包含的数字我应该怎么做才能修复它? (数组应该从1开始)

public class Test {

    public static void main(String[] args) {
        //my max number
        int max=5;
        //my unordered array
        int[] A={1,2,3,5};
        
        //creating the ordered array
        int[] B=new int[max];
        int num=1;
        for (int i = 0; i < max; i++) {
            B[i]=num;
            num++;
        }
        //checking 
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B.length; j++) {
                if (A[i]==B[j]) {
                    System.out.println(B[j]);
                    
                }
            }
        }
    }
        
    
}

【问题讨论】:

  • 对于BB[j] == j + 1中的所有j。所以你的比较实际上是if (A[i] &gt; 0 &amp;&amp; A[i] &lt;= max)(使内循环变得毫无意义)。您需要遍历整个数组以检查其中是否存在数字,但它会是那个检查循环你会知道你寻找的数字是否在数组中。如果您愿意编写新方法,boolean isInArray(int[] array, int numToFind) {...} 可能有助于简化事情。

标签: java arrays


【解决方案1】:

一种简洁的方法是将输入数组转换为 Set,然后遍历所有要检查的数字,使用 .contains() 方法确定每个数字是否在 Set 中:

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        int max = 5;
        Integer[] A={1,2,3,5};

        Set<Integer> s = new HashSet<>();
        Collections.addAll(s, A);

        for (int i = 1; i <= max; i++)
            if (!s.contains(i))
                System.out.println(i);
    }
}

如果你想避免创建 Set 对象的开销,你可以创建一个你自己的函数,它在你的原始数组上执行与 Set 的 contains() 方法等效的函数:

public class Test {

    public static boolean contains(Integer[] arr, int x) {
        for (int j = 0; j < arr.length; j++)
            if (arr[j] == x)
                return true;
        return false;
    }

    public static void main(String[] args) {
        int max = 5;
        Integer[] A={1,2,3,5};

        for (int i = 1; i <= max; i++)
            if (!contains(A, i))
                System.out.println(i);
    }
}

第一种方法对于大型阵列更有效(更快),而第二种方法对于小型阵列更有效。

无论哪种情况,结果都是:

4

另一种方法是对数组进行排序,然后使用 Arrays.binarySearch() 对数组进行二进制搜索。如果您的传入数组始终已经排序,这将特别有吸引力。

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 2019-11-29
    • 2017-06-16
    • 2014-07-20
    • 1970-01-01
    • 2019-12-26
    • 2022-01-19
    • 1970-01-01
    • 2017-01-24
    相关资源
    最近更新 更多