2013-07-22 87 views
0

如果給定數組調用x(由用戶在另一個方法中輸入)包含重複值,我試圖讓方法(duplicateates)返回true。否則,它將返回false。而不是檢查整個數組,它被初始化爲100,它將只檢查輸入值的數量,這個數值用一個全局計數器跟蹤:numElementsInX。Java,如果數組包含重複值,則返回true

完成此操作的最佳方法是什麼?

public static boolean duplicates (int [] x) 

我提示用戶數據,像這樣:

public static void readData (int [] x, int i){ 

    Scanner input = new Scanner(System.in); 
    System.out.println("Please enter integers, enter -999 to stop"); 

    while (i <= 99) { 
     int temp = input.nextInt(); 
      if(temp == -999){ 
       break; 
      } 
      else { 
       x[i++]=temp; 
      } 

    // else 

}//end while 
     printArray(x,i); 


}//end readData 

public static void printArray(int [] x, int numElementsInX){ 

int n = numElementsInX; 

for (int i = 0; i < n; i++){ 
    System.out.print(x[i] + " "); 


}//end for 
     System.out.println(); 
}//end printArray 

我肯定有一個更好的方式來做到這一點,但是這是怎麼了,我一直至今任教。

+1

你的意思是'numElementsInX'是那裏的元素的數量*如果在'x'中,如果沒有重複的話會是*的數量? – david

+0

編輯:對不起,這是一個全球計數器。不,它是數組中輸入值的數量。用戶最多可以輸入100個值。返回array.length給出了整個初始化數組,而不是隻輸入正確的值? – andrsnn

回答

4

這裏是一個解決方案:

  • 編譯並執行時不會拋出。
  • 根據您的要求使用numElementsInX
  • 一旦發現重複就返回。

這種方法測試數組中的每個成員是否曾經見過。如果有,該方法可以立即返回。如果沒有,則該成員被添加到前面看到的集合中。

public static boolean duplicates (int [] x, int numElementsInX) { 
    Set<Integer> set = new HashSet<Integer>(); 
    for (int i = 0; i < numElementsInX; ++i) { 
     if (set.contains(x[i])) { 
      return true; 
     } 
     else { 
      set.add(x[i]); 
     } 
    } 
    return false; 
} 

這是sample program containing the above code

4

這應該這樣做。

public boolean containsDuplicates(Integer[] x) { 
    return new HashSet<Integer>(Arrays.asList(x)).size() != x.length 
} 

你不需要numElementsInX,因爲這是一樣的x.length

編輯從路易後評論。 Arrays.asList不適用於int數組。

爲int []轉換爲整數試試這個問題How to convert int[] to Integer[] in Java?

或做soemthing這樣的(未經測試,但來自內存)

Integer[] newArray = new Integer[a.length]; 
System.arraycopy(a, 0, newArray, 0, a.length); 
+1

只比較輸入值的大小,而不是數組的整個初始化長度。因此櫃檯?它超越了我,但生病嘗試拼湊它除了謝謝! – andrsnn

+0

從理解開始,'Set's不允許重複元素並從那裏開始。 – roippi

+0

什麼是一組?對不起還在這裏學習。 – andrsnn

1

這當然不是最有效的方式,但由於你不知道Sets的是,你可以使用兩個循環:

public static boolean duplicates (int [] x){ 
    for (int i=0; i<numElementsInX; i++){ 
     for (int j=i+1; j<numElementsInX; j++){ 
      if (x[j]==x[i]) return true; 
     } 
    } 
    return false; 
} 
+0

這假設有序數組不是嗎? – RNJ

+2

否 - 它將每個元素與每個其他元素進行比較。它不需要額外的空間,但在最壞的情況下,它的時間是O(n^2)。 –

0

「set.add()」返回true,如果元素不在集合中,則返回true,否則返回false。我們可以利用它並擺脫上面解決方案中的「set.contains()」。

public static boolean duplicates (int[] x, int numElementsInX) { 
    Set<Integer> myset = new HashSet<>(); 
    for (int i = 0; i < numElementsInX; i++) { 
     if (!myset.add(x[i])) { 
      return true; 
     } 
    } 
    return false; 
} 
相關問題