快速數組中是否存在某一個值,java有內置的方法
Arrays.binarySearch
查看了jdk源碼,是快排的方式去查找的。
private static int binarySearch0(Object[] a, int fromIndex, int toIndex,
Object key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
@SuppressWarnings("rawtypes")
Comparable midVal = (Comparable)a[mid];
@SuppressWarnings("unchecked")
int cmp = midVal.compareTo(key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
所以時間複雜度是O(n log n)
如果是輸入的數組不是有序的,那就會出現bug
看個例子:
import java.util.Arrays;
public class hello {
public static void main(String[] args) {
String aa[]=new String[]{"b","c","a","cc"};
System.out.println(aa[Arrays.binarySearch(aa,"a")]);
}
}
是會報錯的,
但是給了排序之後就不一樣了
import java.util.Arrays;
public class hello {
public static void main(String[] args) {
String aa[]=new String[]{"b","c","a","cc"};
Arrays.sort(aa);
System.out.println(aa[Arrays.binarySearch(aa,"a")]);
}
}
關於Arrays.sort,排序方法小於MIN_MERGE = 32 是一種方法,大於是另外一種方法,後面有時間再去看了。
當然檢查數組還有另外一個方法,轉換list直接contains,比較直接有效。
public class hello {
public static void main(String[] args) {
String aa[]=new String[]{"b","c","a","cc"};
System.out.println(Arrays.asList(aa).contains("ff"));
System.out.println(Arrays.asList(aa).contains("c"));
}
}
兩種查找哪種更快,後面有時間再分析
本想就此收尾,發現了一個問題,關於int數組的問題
是不是覺得int也可以這樣寫呢
int[] int_a =new int[]{1,4};
int r=4;
if (!(Arrays.asList(int_a).contains(r))){
System.out.println("不存在");
}else{
System.out.println("存在");
}
是不是有點疑惑呢?其實也沒什麼疑惑的,int不是一個類,它是一個數據類型,在asList的時候會轉換錯誤
Integer[] int_b =new Integer[]{1,4};
int rrr=1;
if (!(Arrays.asList(int_b).contains(rrr))){
System.out.println("不存在");
}else{
System.out.println("存在");
}
這樣就可以啦