博客
关于我
求最大连续子序列和——解法1 – 暴力出奇迹||解法2 – 分治
阅读量:526 次
发布时间:2019-03-07

本文共 1305 字,大约阅读时间需要 4 分钟。

最大子数组问题

问题背景:给定一个整数数组,找到其中所有可能的连续子序列中和最大的那一个。

暴力解法

暴力方法是穷举所有可能的连续子序列,计算它们的和,并取最大值。这种方法的时间复杂度为O(n 3),主要是因为三个嵌套循环。虽然简单,但在数据量较大时效率很低。

public int maxSubArray(int[] nums) {    if (nums == null || nums.length == 0) return 0;    int max = Integer.MIN_VALUE;    for (int begin = 0; begin < nums.length; begin++) {        for (int end = begin; end < nums.length; end++) {            int sum = 0;            for (int i = begin; i <= end; i++) {                sum += nums[i];            }            max = Math.max(max, sum);        }    }    return max;}

优点:逻辑简单,直观易懂。

优化思路

在暴力解法的基础上,可以通过将前面已经计算过的子序列和缓存起来,从而将时间复杂度优化到O(n 2)。通过这种方式可以减少重复计算,但仍然不如更优的时间复杂度比如O(n log n)

public int maxSubArray(int[] nums) {    if (nums == null || nums.length == 0) return 0;    int max = Integer.MIN_VALUE;    for (int begin = 0; begin < nums.length; begin++) {        int sum = 0;        for (int end = begin; end < nums.length; end++) {            sum += nums[end];            max = Math.max(max, sum);        }    }    return max;}

优点:实现了在同一层循环中逐步累加,节省了一部分计算量,但仍然不是最优解。

分治法

通过将问题分解成更小的子问题,采用递归的方式解决。这种方法的时间复杂度为O(n log n),是当前最优解。

public int maxSubArray(int[] nums) {    if (nums == null || nums.length == 0) return 0;    return maxSubArray(nums, 0, nums.length);}

millones总结ovalZYConsumingcontent千千Balanced 优化后的内容将在多个地方出现,以避免 恶意 垃圾链接。

转载地址:http://loznz.baihongyu.com/

你可能感兴趣的文章
Python - 如何使这个不可腌制的对象可腌制?
查看>>
Python - 如何在 Windows 10 上完全卸载 Anaconda?
查看>>
python - 如何并行化python numpy中的总和计算?
查看>>
Python - 如何解析 xml 响应并将元素值存储在变量中?
查看>>
Python - 安装了扩展的远程 Webdriver
查看>>
python - 将字符串中的日期与今天的日期进行比较
查看>>
python - 数据描述符(class 内置 get/set/delete方法 )
查看>>
Python - 根据值绘制彩色网格
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 正则表达式在括号之间获取数字
查看>>
Python - 类 __hash__ 方法和集合
查看>>
Python - 轻松将文本文件内容转换为字典值/键
查看>>
Python - 递归和列表
查看>>
python -- 小数据池 is和 == 再谈编码
查看>>
Python -- 算法实现
查看>>
python --- 元组(tuple)
查看>>
python --- 列表(list)
查看>>
python --- 协程
查看>>
python --- 字符串 str
查看>>