一、有四種方式查詢數組中是否包含某個值
1、使用List
public static boolean useList(String[] arr, String targetValue) { return Arrays.asList(arr).contains(targetValue); }
2、使用Set
public static boolean useSet(String[] arr, String targetValue) { Set<String> set = new HashSet<String>(Arrays.asList(arr)); return set.contains(targetValue); }
3、使用簡單的循環
public static boolean useLoop(String[] arr, String targetValue) { for(String s: arr){ if(s.equals(targetValue)) return true; } return false; }
4、使用Arrays.binarySearch(),但這個方法只接受已經排好序的數組
public static boolean useArraysBinarySearch(String[] arr, String targetValue) { int a = Arrays.binarySearch(arr, targetValue); if(a > 0) return true; else
return false; }
二、計算以上四種方式的時間復雜度
1、測試數組的元素個數分別為:5 , 1000, 10000
public static void main(String[] args) { String[] arr = new String[] { "CD", "BC", "EF", "DE", "AB"}; //use list
long startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useList(arr, "A"); } long endTime = System.nanoTime(); long duration = endTime - startTime; System.out.println("useList: " + duration / 1000000); //use set
startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useSet(arr, "A"); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("useSet: " + duration / 1000000); //use loop
startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useLoop(arr, "A"); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("useLoop: " + duration / 1000000); //use Arrays.binarySearch()
startTime = System.nanoTime(); for (int i = 0; i < 100000; i++) { useArraysBinarySearch(arr, "A"); } endTime = System.nanoTime(); duration = endTime - startTime; System.out.println("useArrayBinary: " + duration / 1000000); }
Result:
useList: 13 useSet: 72 useLoop: 5 useArraysBinarySearch: 9
Use a larger array(1K):
String[] arr = new String[1000]; Random s = new Random(); for(int i=0; i< 1000; i++){ arr[i] = String.valueOf(s.nextInt())
Result:
useList: 112 useSet: 2055 useLoop: 99 useArrayBinary: 12
Use a larger array(1K):
String[] arr = new String[10000]; Random s = new Random(); for(int i=0; i< 10000; i++){ arr[i] = String.valueOf(s.nextInt()); }
Result:
useList: 1590 useSet: 23819 useLoop: 1526 useArrayBinary: 12
三、總結
從以上結果可以清晰的看出,使用簡單的循環比使用集合更高效,很多開發者更多的使用第一種方式,但是第一種方式並不是最高效的,因為使用集合的時候,需要從數組無序的讀取元素,再存儲到結合中,這個過程非常耗時;
實際上,一個排序好的List或者Tree時間復雜度僅為:O(log(n)),而HashSet的效率更高:O(1)
