有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

检查数组中是否存在一个范围内的所有值的最佳方法是什么?(爪哇)

我的任务是确定1,2,3中的每一个值。。。n在无序的int数组中。我不确定这是否是最有效的方法,但我创建了一个名为range的int[],它只包含范围[I]中从1到n的所有数字(范围[0]=1,范围[1]=2,等等)。然后我尝试使用containsAll方法检查给定数字的数组是否包含范围数组中的所有数字。然而,当我测试它时,它返回false。我的代码有什么问题,还有什么更有效的方法来解决这个问题

public static boolean hasRange(int [] givenNums, int[] range) {
    boolean result = true;
    int n = range.length;
    for (int i = 1; i <= n; i++) {
    if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
           result = false;
     }
   }
    return result;
}

(我很确定我应该手动完成这项工作,而不是使用containsAll方法,因此如果有人知道如何用这种方式解决它,那将特别有用!)

对于好奇的人来说,这种方法的含义如下:

public static void checkMatrix(int[][] intMatrix) {
    File numberFile = new File("valid3x3") ;
    intMatrix= readMatrix(numberFile);
    int nSquared = sideLength * sideLength;
    int[] values = new int[nSquared];
    int[] range = new int[nSquared];
    int valCount = 0;

    for (int i = 0; i<sideLength; i++) {
        for (int j=0; j<sideLength; j++) {

            values[valCount] = intMatrix[i][j];
            valCount++;
        }
    }

    for (int i=0; i<range.length; i++) {
        range[i] = i+1;
    }

    Boolean valuesThere = hasRange(values, range);

值打印时为假


共 (3) 个答案

  1. # 1 楼答案

    第一款:

    if (condition == false) // Works, but at the end you have if (true == false) or such
    if (!condition) // Better: not condition
    
    // Do proper usage, if you have a parameter, do not read it in the method.
    File numberFile = new File("valid3x3") ;
    intMatrix = readMatrix(numberFile);
    checkMatrix(intMatrix);
    
    public static void checkMatrix(int[][] intMatrix) {
        int nSquared = sideLength * sideLength;
        int[] values = new int[nSquared];
    

    然后是问题。值得称赞的是,列表甚至更好的集合方法是精确的抽象级别:深入细节是不明智的。然而,这正是我们想要的

    要知道[1,…,n]范围内的每个元素是否都存在

    • 你可以浏览给定的数字
    • 对于每一个数字,看看它是否在这个范围内是新的,标记为不再是新的
    • 如果达到n个新数字:返回true

      int newRangeNumbers = 0;
      boolean[] foundRangeNumbers = new boolean[n]; // Automatically false
      

    想出更好的名字

  2. # 2 楼答案

    Arrays.asList(givenNums).
    

    这和你想的不一样。它返回一个带有单个元素的List<int[]>,它不会将givenNums中的值框到Integer并返回List<Integer>。这就解释了为什么你的方法不起作用

    使用Java8流,假设您不想对givens进行永久排序。如果你不在乎,就去掉copyOf()

        int[] sorted = Arrays.copyOf(givens,givens.length);
        Arrays.sort(sorted);
        boolean result = Arrays.stream(range).allMatch(t -> Arrays.binarySearch(sorted, t) >= 0);
    
  3. # 3 楼答案

    你说你有一个一维数组,对吗? 好的那我想你是在考虑复杂化。 我试着解释另一种方法来检查数组中的所有数字是否都是按数字顺序排列的

    例如,数组具有以下值:

    int[] array = {9,4,6,7,8,1,2,3,5,8};
    

    首先,你可以订购simpel阵列

    Arrays.sort(array);
    

    完成此操作后,可以在数组中循环并与索引进行比较,如(在方法中):

    for(int i = array[0];i < array.length; i++){
      if(array[i] != i) return false;