简体   繁体   English

尽管使用 JAVA 的顺序不同,但检查两个 arrays 是否相等的方法。 我收到有关我的退货声明的错误

[英]Method to check if two arrays are equal despite different order using JAVA. I'm getting errors about my return statement

I've been trying at this for the entire day.我一整天都在尝试这个。 I have an assignment and basically I need to check if 2 arrays have the same elements (w/o having the same order. My idea is我有一个任务,基本上我需要检查 2 arrays 是否具有相同的元素(没有相同的顺序。我的想法是

1- check if theyre the same length. 1-检查它们是否相同的长度。 if not then theyre obviously not the same如果不是,那么它们显然不一样

2- to read one element in array 1 and then look for it in the other array, then increment a counter and at the end check if the counter is equal to the length of the array. 2-读取数组1中的一个元素,然后在另一个数组中查找它,然后增加一个计数器,最后检查计数器是否等于数组的长度。

i'm getting this error: missing return statement我收到此错误:缺少返回语句

i need to say that i'm not allowed to use things like sort or hash to solve this since i've seen methods with these before but they cant help here.我需要说我不允许使用 sort 或 hash 之类的东西来解决这个问题,因为我以前见过这些方法,但他们在这里帮不上忙。

public static boolean isSame(int[] ArrayX,int [] ArrayY){

       int count=0;

   if(ArrayX.length!=ArrayY.length)// to check that they have the same size
       return false;

 for (int i=0;i<ArrayX.length;i++){

       for(int j=0;j<ArrayY.length;j++)//this loop is to search for element[i] in array Y
          {
           if (ArrayY[j]==ArrayX[i])

               count++;
           }
           }
 if (count==ArrayX.length) //to check that number of identical elements is equal to the size 
  return true;
   }

 

You're just missing a default return statement in the end.最后,您只是缺少默认的 return 语句。 Add "return false" when they're not equal当它们不相等时添加“return false”

if (count==ArrayX.length) {
  return true;
}
return false;

Also curious, You mentioned you cannot use hash.也很好奇,你提到你不能使用 hash。 Are you referring to hash based data structures?您指的是基于 hash 的数据结构吗?

You need to return default condition when your condition is false.当您的条件为假时,您需要返回默认条件。 Updated the code.更新了代码。

public static boolean isSame(int[] ArrayX,int [] ArrayY){

       int count=0;

   if(ArrayX.length!=ArrayY.length)// to check that they have the same size
       return false;

 for (int i=0;i<ArrayX.length;i++){

       for(int j=0;j<ArrayY.length;j++)//this loop is to search for element[i] in array Y
          {
           if (ArrayY[j]==ArrayX[i])

               count++;
           }
           }
 if (count==ArrayX.length) //to check that number of identical elements is equal to the size 
  return true;
   }
return false;
}

You can simply order the two arrays and then loop through both.您可以简单地订购两个 arrays,然后循环通过两者。 If either their count is mismatched or the ordering isn't the same, you can efficiently return the failure.如果它们的计数不匹配或顺序不同,您可以有效地返回失败。

Avoids nesting for loops!避免嵌套 for 循环!

import java.util.Arrays;

public static boolean isSame(int[] ArrayX, int [] ArrayY)
{    
    if (ArrayX.length != ArrayY.length) {// to check that they have the same size
        return false;
    }

    ArrayX = Arrays.sort(ArrayX);
    ArrayY = Arrays.sort(ArrayY);
    
    for (int i=0; i < ArrayX.length; i++){
        
        if (ArrayX[i] != ArrayY[i]){
            return false;
        }
    }

    return true;
}

Note: this hasn't been tested.注意:这还没有经过测试。 Please comment if it needs amending.如果需要修改请评论。 Thank-you.谢谢。

You can just return the condition and avoid extra if else.您可以只返回条件并避免额外的条件。

public static boolean isSame(int[] ArrayX,int [] ArrayY){

        if(ArrayX.length!=ArrayY.length)// to check that they have the same size
            return false;

        // Sort both arrays
        Arrays.sort(ArrayX);
        Arrays.sort(ArrayY);
        for (int i=0;i<ArrayX.length;i++){
            if (ArrayX[i]!=ArrayY[i]){ // Compare elements
                return false;  // 
            }
        }
        return true;
    }

Time complexity is ( O(n log(n)) + O(n log(n)) + O(n) ) ~ (n)时间复杂度为 ( O(n log(n)) + O(n log(n)) + O(n) ) ~ (n)

You have two return statements:您有两个返回语句:

 if(ArrayX.length!=ArrayY.length)// to check that they have the same size
   return false;

and

   if (count==ArrayX.length) //to check that number of identical elements is equal to the size 
       return true;
   }

both are conditionally, you need something which gets returned in case no of these if statements are met!两者都是有条件的,如果没有满足这些 if 语句,您需要返回一些东西!

If the count does not match up you probably want to add a return false;如果计数不匹配,您可能需要添加return false; because they definitely do not match.因为他们绝对不匹配。

Also see this Answer .另请参阅此答案

Check if any of the arrays are null or not the same length, then loop-over them to check if any equals and increment the counter and break the inner-loop.检查 arrays 中的任何一个是否为 null 或不同的长度,然后循环它们以检查是否有任何等于并增加counter并中断内循环。

    public static boolean isSame(int[] arrayX, int[] arrayY) {
        if (arrayX == null || arrayY == null || arrayX.length != arrayY.length)
            return false;

        int count = 0;
        int len = arrayX.length;

        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                if (arrayY[j] == arrayX[i]) {
                    count++;
                    break;
                }
            }
        }
        return count == len ? true : false;
    }

, main function , main function

    public static void main(String[] args) {
        System.out.println(isSame(new int[] { 4, 5, 6, 7, 9 }, new int[] { 9, 6, 7, 4, 5 }));
    }

, output , output

true

Try this.尝试这个。 Convert arrays into Hashmaps that of the value vs how many times the value tursn up in the array.将 arrays 转换为值的 Hashmaps 与该值在数组中出现的次数。 Then compare the maps.然后比较地图。 I think it's O(n) time.我认为现在是 O(n) 时间。

public static void main(String[] args)
{
    int[] myArray =  {1,2,3,4,5,6,7,8,9,8,7};
    int[] myArray2 =  {6,7,8,9,8,1,2,3,4,5,7};
    HashMap<Integer, Integer> arrayMap = convertArraytoMap(myArray);
    HashMap<Integer, Integer> arrayMap2 = convertArraytoMap(myArray2);


    boolean answer = compareMaps(arrayMap,arrayMap2);
    System.out.println(answer);
    

}//main

//-------------------------------------------------------------------------//


private static HashMap<Integer, Integer> convertArraytoMap(int[] array){
    
    //Map of integer entry versus how many times it turns up
    HashMap<Integer, Integer> arrayMap = new HashMap<Integer, Integer>();
 
    for(int item : array){
        if(arrayMap.containsKey(item))
            arrayMap.put(item, arrayMap.get(item)+1);
        else
        arrayMap.put(item, 1) ;
        
    }//for
    
    return arrayMap;
    
}//convertArraytoMap


//-------------------------------------------------------------------------//

private static boolean compareMaps(   HashMap<Integer, Integer> arrayMap1,    HashMap<Integer, Integer> arrayMap2){
   
     for (int key : arrayMap1.keySet()) {
        
        //Does the 2nd array contain some number of this key
        if(!arrayMap2.containsKey(key))
            return false;
            
        //Does the 2nd array contain the exact same number of this key
        if(arrayMap1.get(key) != arrayMap2.get(key))
            return false;
            
            
    }//for
    
    return true;

}//compareMaps

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在使用 Java 制作工资单。 如果我的数学公式看起来是正确的,为什么我会得到错误的净工资? - I'm making a payroll using Java. Why am I getting the wrong net pay if my mathematical formulas seem correct? 如何使用递归检查两个二维数组是否相等? 爪哇 - How can I check if two 2D Arrays are equal using recursion? Java 我正在尝试使用Java更新oracle数据库中的密码。 难道我做错了什么? - I'm trying to update my password in oracle database using Java. Am I doing something wrong? 我想将三个不同的字符串传递给java中的main方法。 我该怎么做呢? - I want to pass three different strings to my main method in java. How do I do this? 我有不同版本的javac和java。 我正在尝试在终端上运行.java文件。 但是它可以在日食中工作 - I have different versions of javac and java. I'm trying to run my .java file on terminal. But it works in eclipse 我正在尝试通过使用此代码来比较两个数组,但出现错误:java.lang.AssertionError - I'm trying to do comparision of two arrays by using this code, but I'm getting error: java.lang.AssertionError 在Java中的方法中返回两个数组 - Return two arrays in a method in Java 我正在尝试遍历 Java 中的两个数组,同时还检查这些值是否相等 - I'm trying to iterate through two arrays in Java, while also checking to see if the values are equal 是Java中的数组等于方法 - are arrays equal method in java 我对Java中的返回方法感到困惑 - I'm confused about return methods in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM