2017-08-01 83 views
0

我正在寫一個函數,它返回兩個整型數組之間的差異。我假設輸入數組中的所有元素都是唯一的,而且輸入數組也沒有排序。例如:找到兩個整數數組之間的差異

輸入:
arr1 = [1,2,3,5,4]
arr2 = [1,2,3]

預期輸出:[4,5]

我的輸出:[1,2,3,4,5](當第一陣列比第二大)

當我使第二陣列大於第一,我得到ArrayIndexOutOfBoundsException

public class Test{ 

    public static void main(String args[]) 
    { 

     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter length of first array"); 
     int ml = sc.nextInt(); 
     System.out.println("Enter length of second array"); 
     int nl = sc.nextInt(); 
     int m[] = new int[ml]; 
     int n[] = new int[nl]; 
     System.out.println("Enter elements of first array"); 
     for(int i=0;i<ml;i++) 
     { 
      m[i] = sc.nextInt(); 
     } 

     System.out.println("Enter elements of second array"); 
     for(int j=0;j<nl;j++) 
     { 
      m[j] = sc.nextInt(); 
     } 
     ArrayList<Integer> arr1 = new ArrayList<Integer>(); 
     for(int i: m){ arr1.add(i);} 
     ArrayList<Integer> arr2 = new ArrayList<Integer>(); 
     for(int j: n){ arr2.add(j);} 
     if(ml>nl) 
     { 
      arr1.removeAll(arr2); 
      System.out.println(arr1); 
     } 
     else 
     { 
      arr2.removeAll(arr1); 
      System.out.println(arr2); 
     } 
    } 
} 
+1

我強烈建議你通過這個步驟與調試器。你將能夠看到到底發生了什麼。 –

+1

使用try catch塊進行適當的異常處理。 – Tehmina

回答

2

在第二次迭代,你應該使用的n[j] = ...代替m[j] = ... 您應該使用更具描述性的變量名,以防止事情樣的事情的發生。

+0

謝謝,這解決了它。我會記住將來會保留更好的名字。 – coder8888

-3

那麼這在我腦海的第一個想法是這樣的:

if(array1.Length>array2.Length){ 
foreach(int k in array1){ 
foreach(int l in array2){ 
if(k==l){ 
k=null; 
} 
} 
} 
}else{ 
foreach(int l in array2){ 
foreach(int k in array1){ 
if(l==k){ 
l=null; 
} 
} 
} 
} 


未經檢驗的,只有在定理適用於當一個陣列是另一個的子集,但希望它的一個開始: )

+0

這不是Java。如果它是Java,它將無法工作,因爲int []不能存儲空值。 –

0

如果它不是讓你在陣列/反覆練習的功課,你可以考慮使用Set爲更簡單的邏輯:

// pseudo-code 
Set<Integer> set1 = new HashSet<>(array1); 
Set<Integer> set2 = new HashSet<>(array2); 

// Using Guava 
Set<Integer> diff = Sets.symmetricDifference(set1, set2); 

// Java only 
Set<Integer> diff1 = new HashSet<>(set1); 
diff1.removeAll(set2); // diff1 contains entries in array1 but not 2 
Set<Integer> diff2 = new HashSet<>(set2); 
diff2.removeAll(set1); // diff2 contains entries in array2 but not 1 

Set<Integer> diff = new HashSet<>(set1); 
diff.addAll(set2); 


// Java only, using stream 
return Stream.concat(set1.stream(), set2.stream()) 
      .filter(i -> ! (set1.contains(i) && set2.contains(i))) 
      .collect(Collectors.toSet()); 
0

您可以檢查元素第二個存在如果不能夠增加輸出數組如下:

int[] array1 = new int[] { 1, 2, 3, 4, 5 }; 
    int[] array2 = new int[] { 1, 2, 3 }; 
    List<Integer> output = new ArrayList<>(); 
    for (int i = 0; i < array1.length; i++) { 
     boolean flag = false; 
     for (int j = 0; j < array2.length; j++) { 
      if (array1[i] == array2[j]) { 
       flag = true; 
       break; 
      } 
     } 
     if (!flag) { 
      output.add(array1[i]); 
     } 
    } 

    System.out.println(output); 
相關問題