2015-10-20 69 views
0

搜索重複我有2維數組,如:在2維數組

{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10}, 
{6 , 10, 50, 12, 11, 29, 68 , 13, 14}, 
{46, 50, 90, 52, 51, 69, 108, 53, 54} 

我怎樣才能找到重複的元素,如'6', '46' and '50'

我的代碼查找連續的重複:

for (int i = 0; i < a2.length; i++) { 
     for (int j = 0; j < a2[i].length; j++) { 
      cursor = a2[i][j]; 

      if(j + 1 < a2[i].length){ 
       if(cursor == a2[i][j + 1]){ 
        System.out.println(cursor + "has duplicate in this array"); 
       } 
      } 
     } 
    } 
+0

如果要刪除重複的元素,把所有的數字放在一個Set中。 – Rehman

+1

是否要打印重複元素或查找數組是否包含重複項 –

+0

'j'的範圍不是0到'a.length'。它應該是0到'a [i] .length'。此外,這段代碼沒有找到通用的重複項。它只查看連續的重複項。這是你的意圖嗎? – lurker

回答

0

通過迭代所有元素,並將其保存在臨時設置。
當您遇到重複時,該列表將包含它。

import java.util.HashSet; 
import java.util.HashSet; 

public class HelloWorld 
{ 
    public static void main(String[] args) 
    { 
    int[][] arr = { 
     {2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10}, 
     {6 , 10, 50, 12, 11, 29, 68 , 13, 14}, 
     {46, 50, 90, 52, 51, 69, 108, 53, 54} 
    }; 

    HashSet<Integer> elements = new HashSet<>(); 
    HashSet<Integer> duplicates = new HashSet<>(); 
    for (int i = 0; i < arr.length; i++) { 
     for (int j = 0; j < arr[i].length; j++) { 
      if(elements.contains(arr[i][j])) { 
       duplicates.add(arr[i][j]); 
      } 
      elements.add(arr[i][j]); 
     } 
    } 

    System.out.println(duplicates.toString()); 
    } 
} 

輸出:

[50,6,10,46]

+0

有沒有沒有使用「哈希集」的解決方案? – OCY

+0

我必須問爲什麼? – Cyrbil

+1

@OCY - 是的。你爲什麼不試着爲自己找出答案?你會學到更多的方式。 –

0

嘗試驗證碼 -

import java.util.Arrays; 
import java.util.List; 

public class ArrayTest { 

    public static void main(String[] args) { 

     Integer[][] myarray = new Integer[][]{ 
        { 10, 20, 30, 40 }, 
        { 50, 77, 60, 70 }, 
        { 33, 22, 88, 99 }, 
        { 21, 66, 65, 21 } 
       }; 
     int i,j; 
     for(i=0;i<myarray.length;i++) 
     { 
      for(j=0;j<myarray.length;j++) 
      { 
       int temp= myarray[i][j]; 
       myarray[i][j]=0; 
       List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(i)); 
       Boolean b=rowvalues.contains(temp) ; 
       if(b==true) 
       { 
        System.out.println("duplicate at ["+i+"]["+j+"] is: "+temp); 
       } 
       myarray[i][j]=temp; 
      } 
     } 




    } 

} 
+0

這並沒有找到所有重複項,因爲它只搜索當前的子數組。 你也可以重構'Arrays.asList(Arrays.asList(myarray).get(i))'只做一次轉換,而不是每一次循環。 – Cyrbil