1. 程式人生 > >如何檢查一個數組中是否有某個值?

如何檢查一個數組中是否有某個值?

如何檢查一個沒有排序的陣列中是否含有某個值?這個操作在Java中經常使用,也是很有用的;但採取的方式不同,時間複雜度也不同;

以下提供了4種方式: 

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():

 下面的程式碼是錯誤的,列出來只是為了多提供一個而已。binarySearch() 只能用在已經排了序的陣列上。

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

 時間複雜度: 

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);
}

結果:

    useList:  13

    useSet:  72

    useLoop:  5

    useArraysBinarySearch:  9

使用一個大一點的陣列呢?(1K)

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

 結果:

    useList:  112

    useSet:  2055

    useLoop:  99

    useArrayBinary:  12

使用一個再大點的陣列呢?(10K) 

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

結果:

    useList:  1590

    useSet:  23819

    useLoop:  1526

    useArrayBinary:  12

很明顯,使用簡單的for迴圈是最高效的。

如果使用Arrays.binarySearch(),那陣列必須是已經排序。

事實上,一個已經排序的 List 或者 Tree 複雜度為O(log(n)),  HashSet 為O(1)