在Java中如何高效的判斷數組中是否包含某個元素

轉載自 在Java中如何高效的判斷數組中是否包含某個元素

如何檢查一個數組(無序)是否包含一個特定的值?這是一個在Java中經常用到的並且非常有用的操作。同時,這個問題在Stack Overflow中也是一個非常熱門的問題。在投票比較高的幾個答案中給出了幾種不同的方法,但是他們的時間複雜度也是各不相同的。本文將分析幾種常見用法及其時間成本。

檢查數組是否包含某個值的方法

使用List

  1. public static boolean useList(String[] arr, String targetValue) {
  2.    return Arrays.asList(arr).contains(targetValue);
  3. }

使用Set

  1. public static boolean useSet(String[] arr, String targetValue) {
  2.    Set<String> set = new HashSet<String>(Arrays.asList(arr));
  3.    return set.contains(targetValue);
  4. }

使用循環判斷

  1. public static boolean useLoop(String[] arr, String targetValue) {
  2.    for(String s: arr){
  3.        if(s.equals(targetValue))
  4.            return true;
  5.    }
  6.    return false;
  7. }

使用Arrays.binarySearch()

Arrays.binarySearch()方法只能用於有序數組!!!如果數組無序的話得到的結果就會很奇怪。

查找有序數組中是否包含某個值的用法如下:

  1. public static boolean useArraysBinarySearch(String[] arr, String targetValue) {
  2.    int a =  Arrays.binarySearch(arr, targetValue);
  3.    if(a > 0)
  4.        return true;
  5.    else
  6.        return false;
  7. }

時間複雜度

下面的代碼可以大概的得出各種方法的時間成本。基本思想就是從數組中查找某個值,數組的大小分別是5、1k、10k。這種方法得到的結果可能並不精確,但是是最簡單清晰的方式。

  1. public static void main(String[] args) {
  2.    String[] arr = new String[] {  "CD",  "BC", "EF", "DE", "AB"};
  3.    //use list
  4.    long startTime = System.nanoTime();
  5.    for (int i = 0; i < 100000; i++) {
  6.        useList(arr, "A");
  7.    }
  8.    long endTime = System.nanoTime();
  9.    long duration = endTime - startTime;
  10.    System.out.println("useList:  " + duration / 1000000);
  11.    //use set
  12.    startTime = System.nanoTime();
  13.    for (int i = 0; i < 100000; i++) {
  14.        useSet(arr, "A");
  15.    }
  16.    endTime = System.nanoTime();
  17.    duration = endTime - startTime;
  18.    System.out.println("useSet:  " + duration / 1000000);
  19.    //use loop
  20.    startTime = System.nanoTime();
  21.    for (int i = 0; i < 100000; i++) {
  22.        useLoop(arr, "A");
  23.    }
  24.    endTime = System.nanoTime();
  25.    duration = endTime - startTime;
  26.    System.out.println("useLoop:  " + duration / 1000000);
  27.    //use Arrays.binarySearch()
  28.    startTime = System.nanoTime();
  29.    for (int i = 0; i < 100000; i++) {
  30.        useArraysBinarySearch(arr, "A");
  31.    }
  32.    endTime = System.nanoTime();
  33.    duration = endTime - startTime;
  34.    System.out.println("useArrayBinary:  " + duration / 1000000);
  35. }

運行結果:

  1. useList:  13
  2. useSet:  72
  3. useLoop:  5
  4. useArraysBinarySearch:  9

使用一個長度爲1k的數組

  1. String[] arr = new String[1000];
  2. Random s = new Random();
  3. for(int i=0; i< 1000; i++){
  4.    arr[i] = String.valueOf(s.nextInt());
  5. }

結果:

  1. useList:  112
  2. useSet:  2055
  3. useLoop:  99
  4. useArrayBinary:  12

使用一個長度爲10k的數組

  1. String[] arr = new String[10000];
  2. Random s = new Random();
  3. for(int i=0; i< 10000; i++){
  4.    arr[i] = String.valueOf(s.nextInt());
  5. }

結果:

  1. useList:  1590
  2. useSet:  23819
  3. useLoop:  1526
  4. useArrayBinary:  12

總結

顯然,使用一個簡單的循環方法比使用任何集合都更加高效。許多開發人員爲了方便,都使用第一種方法,但是他的效率也相對較低。因爲將數組壓入Collection類型中,首先要將數組元素遍歷一遍,然後再使用集合類做其他操作。

如果使用Arrays.binarySearch()方法,數組必須是已排序的。由於上面的數組並沒有進行排序,所以該方法不可使用。

實際上,如果你需要藉助數組或者集合類高效地檢查數組中是否包含特定值,一個已排序的列表或樹可以做到時間複雜度爲O(log(n)),hashset可以達到O(1)。

(英文原文結束,以下是譯者注)


使用ArrayUtils

除了以上幾種以外,Apache Commons類庫中還提供了一個ArrayUtils類,可以使用其contains方法判斷數組和值的關係。

  1. import org.apache.commons.lang3.ArrayUtils;
  2. public static boolean useArrayUtils(String[] arr, String targetValue) {
  3.    return ArrayUtils.contains(arr,targetValue);
  4. }

同樣使用以上幾種長度的數組進行測試,得出的結果是該方法的效率介於使用集合和使用循環判斷之間(有的時候結果甚至比使用循環要理想)。

  1. useList:  323
  2. useSet:  3028
  3. useLoop:  141
  4. useArrayBinary:  12
  5. useArrayUtils:  181
  6. -------
  7. useList:  3703
  8. useSet:  35183
  9. useLoop:  3218
  10. useArrayBinary:  14
  11. useArrayUtils:  3125

其實,如果查看ArrayUtils.contains的源碼可以發現,他判斷一個元素是否包含在數組中其實也是使用循環判斷的方式。

部分代碼如下:

  1.    if(array == null) {
  2.        return -1;
  3.    } else {
  4.        if(startIndex < 0) {
  5.            startIndex = 0;
  6.        }
  7.        int i;
  8.        if(objectToFind == null) {
  9.            for(i = startIndex; i < array.length; ++i) {
  10.                if(array[i] == null) {
  11.                    return i;
  12.                }
  13.            }
  14.        } else if(array.getClass().getComponentType().isInstance(objectToFind)) {
  15.            for(i = startIndex; i < array.length; ++i) {
  16.                if(objectToFind.equals(array[i])) {
  17.                    return i;
  18.                }
  19.            }
  20.        }
  21.        return -1;
  22.    }

所以,相比較之下,我更傾向於使用ArrayUtils工具類來進行一些合數祖相關的操作。畢竟他可以讓我少寫很多代碼(因爲自己寫代碼難免有Bug,畢竟apache提供的開源工具類庫都是經過無數開發者考驗過的),而且,效率上也並不低太多。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章