美文网首页数据结构与算法
数据结构与算法分析

数据结构与算法分析

作者: ReentrantSucc | 来源:发表于2018-06-02 10:48 被阅读1次

只要在常数时间内可以将问题的大小削减为其一部分($ \frac{1}{2} $), 那么该算法就是($O(logN)$)

  1. 最大子序列和问题($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;
}
  1. 折半查找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;
    }

相关文章

网友评论

    本文标题:数据结构与算法分析

    本文链接:https://www.haomeiwen.com/subject/sjtrsftx.html