[英]the time complexity of array function
我編寫了一個函數來查找目標值應在給定數組中插入的位置。 我們假設該數組具有不同的值,並按升序排序。 我的解決方案必須是O(log N)時間復雜度
public static int FindPosition(int[] A, int target) {
int a = A.length / 2;
System.out.println(a);
int count = a;
for (int i = a; i < A.length && A[i] < target; i++) {
count++;
}
for (int i = a; i > A.length && A[i] > target; i--) {
count++;
}
return count;
}
此代碼是否具有O(log N)的復雜度?
沒有。
索引中的增量為1
時,就不能期望有比O(n)
更好的解決方案。
如果您的算法完全可行(我認為它不可行),則似乎需要O(n)
步驟。
另外,您說您假設數組已排序,但是無論如何都對其進行了排序。 所以你的代碼是O(n*log(n))
。
而且,對於某些排序算法,嘗試對已經排序的數組進行排序是最糟糕的情況:甚至可能是O(n**2)
。
您正在尋找二進制搜索 。
不,這不是nlogn
public static int FindPosition(int[] A, int target){
/*
Time taken to sort these elements would depend on how
sort function is implemented in java. Arrays.sort has average
time complexity of Ω(n log n), and worst case of O(n^2)
*/
Arrays.sort(A);
/*Time taken to run this loop = O(length of A) or O(N)
where N = arraylength
*/
for(int i=a;i<A.length&&A[i]<target;i++){
count++;
}
/*Time taken to run this loop = O(length of A) or O(N)
where N = arraylength
*/
for(int i=a;i>A.length&&A[i]>target;i--){
count++;
}
return count;
}
現在,時間復雜度將由以上三個中的最長者來表示,因為分配和所有操作都在固定時間內完成。
因此,在最壞的情況下會使您的復雜度為O(n ^ 2)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.