只要在常数时间内可以将问题的大小削减为其一部分($ \frac{1}{2} $), 那么该算法就是($O(logN)$)
- 最大子序列和问题($O(NlogN)$)
public static int maxSubSum(int[] arr) {
int maxSum = 0, thisSum = 0;
for (int i = 0; i < arr.length; i++) {
thisSum += arr[i];
if (thisSum > maxSum) {
maxSum = thisSum;
} else if (thisSum < 0) {
thisSum = 0;
}
}
return maxSum;
}
- 折半查找binary search($O(logN)$)
public static int binarySearch(int[] arr, int x) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high)/2;
if (arr[mid] < x) {
low = ++mid;
} else if (arr[mid] > x) {
high = --mid;
} else {
return mid;
}
}
return -1;
}
网友评论