2014-03-19 43 views
1

我正在编写一个基本程序来比较两个数组中的数据。顺序无关紧要,重复的数字也不重要。目前的输出是说数组数据是相同的。由于阵列数据不同,这不是我想要发生的事情。这是代码,我现在所拥有的:不考虑大小或顺序的Java数组数据比较

public class Algorithm1{ 
public static void main (String[] args){ 

    int[] array1 = {1, 2, 3}; 
    int[] array2 = {1, 2, 3, 4, 5, 6}; 
    int matchCount = 0; 
    boolean match = false; 

for(int j = 0; j < array1.length;j++) { 
    for(int i = 0; i < array2.length;i++){ 
if(array1[j] == array2[i]) 
    matchCount++; 


    } 
} 
if(matchCount >= array1.length && matchCount >= array2.length) 
    match = true; 

if(match = true){ 
    System.out.println("The data in the arrays is the same."); 
       } 
else if(match = false){ 
    System.out.println("The data in the arrays is different."); 
       } 
} 
} 
+0

所以你想要的是检查一个数组是否是另一个的子集? –

+0

@ user3435566你可以尝试在它之前对它进行排序。这种方式的O(nlogn)更快。当使用两个for循环时,它将是O(n^2) – Dexters

回答

0

通过if(match == true)甚至更​​简单,if(match)只需更换if(match = true),你应该可以了吧;)

您写道:

if(match = true) { 
    System.out.println("The data in the arrays is the same."); 
} 

if(match = true)其实:

  • sets matchtrue
  • 测试如果先前表达true ......并进入if :)

作为一个方面说明,我想指出的是,你不需要指定如果(match == false)在else子句...因为如果我们输入else,它已经意味着match != true(即:match == false)。

干杯!

0

这是一个相当简单的错误,很多初学程序员所做的。当比较两个对象,您使用==和设置时,您可以使用=

相反的:

if(match = true){ 
    System.out.println("The data in the arrays is the same."); 
} 
else if(match = false){ 
    System.out.println("The data in the arrays is different."); 
} 

应该是:

if(match == true){ 
    System.out.println("The data in the arrays is the same."); 
} 
else if(match == false){ 
    System.out.println("The data in the arrays is different."); 
} 

那么,在现实中,这是非常多余。说if(match == true)是一样的东西,只是说if(match),无论如何,在else部分,如果匹配不是真的,那么它一定是假的,所以说else if(match == false)是unistsary。你只需要说else

下面是它应该与我所做的修订内容:

if(match){ 
    System.out.println("The data in the arrays is the same."); 
} 
else{ 
    System.out.println("The data in the arrays is different."); 
} 
0

试试这个代码,让我知道,如果你需要更多的解释,如果这是你所需要的

O(nlogn)运行时,如果你有兴趣:)如果你使用散列或设置..它将是O(n)但更高的空间复杂度

import java.io.*; 
import java.util.Arrays; 

class Ideone 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     int[] array1 = {1, 2, 3, 6, 5, 4, 3}; 
     int[] array2 = {1, 2, 3, 4, 5, 6, 4, 4,6}; 
     java.util.Arrays.sort(array1); 
     java.util.Arrays.sort(array2); 
     boolean match = true; 
     int ptr1 = 0; 
     int ptr2 = 0; 
     while(ptr1<array1.length && ptr2<array2.length && array1[ptr1]==array2[ptr2]) 
     { 

      ptr1++;ptr2++; 
      while(ptr1<array1.length && array1[ptr1]==array1[ptr1-1]) 
      { 
       ptr1++; 
      } 
      while(ptr2<array2.length && array2[ptr2]==array2[ptr2-1]) 
      { 
       ptr2++; 
      } 
     } 
     if((ptr1 == array1.length) && (ptr2 == array2.length)) 
      System.out.println("The data in the arrays is the same"); 
     else 
      System.out.println("The data in the arrays is the different"); 
    } 
}