剑指offer——连续子数组的最大和
来源:互联网 发布:魔兽争霸windows语言 编辑:程序博客网 时间:2024/05/22 17:51
1. 题目描述
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?(子向量的长度至少是1)
2. 题目分析
这个题目最直接的方法就是暴力求解。因为题目中描述的是“连续子向量”,所以不用考虑非连续的情况。那么暴力求解的思想就是依次以每个元素为子向量的第一个元素,求其子向量的最大和。时间复杂度 T(n)=n*n
另一种方法就是使用分治法。若将原数组从中间节点分为左右两个部分,和最大的连续子数组可以分为三种情况:
1)最大子数组是左半部分的子集
2)最大子数组是右半部分的子集
3)最大子数组跨越左右两个部分
一次对左右部分进行对半划分,直至划分出的子数组包含一个元素为止。(这里我也不知道怎么说明白啦,不明白的地方直接看代码吧)
3. 题目解答——cpp
暴力破解:
class Solution {public: int FindGreatestSumOfSubArray(vector<int> array) { if(array.size()==0) return 0; int length = array.size(); int sum,ans; ans = array[0]; for(int i = 0;i<length;i++){ //依次以array[i]为第一个元素 sum = 0; for(int j = i;j<length;j++) { //遍历以array[i]为首元素的子数组 sum += array[j]; if (sum > ans) { ans = sum; // 保存当前为止所有遍历结果的最大值 } } } return ans; }};
分治:
class Solution {public: int FindGreatestSumOfSubArray(vector<int> array) { // 判断数组为空的情况 if(array.size()==0) return 0; // 在递归调用中,使用的数组为array的子数组,需要标注起始位置,故写一个帮助函数 return FindFromLCR(array,0,array.size()-1); } // 找到array[left]至array[right]中的最大和子数组 int FindFromLCR(vector<int> array, int left, int right) { int LeftBottomSum, MaxLeftBottomSum; // 情况3的左半部分当前和、最大和 int RightBottomSum, MaxRightBottomSum; // 情况3的右半部分当前和、最大和 int LeftSum, RightSum; // 情况1的最大和、情况2的最大和 int mid; // 当前中间节点 if (left == right){ return array[left]; } LeftBottomSum = 0; mid = (right-left)/2 + left; // 防止溢出的中间节点求取方法 // 求取情况3的左半部分 MaxLeftBottomSum = array[mid]; for(int i = mid;i>=left;i--){ LeftBottomSum += array[i]; if (LeftBottomSum > MaxLeftBottomSum) { MaxLeftBottomSum = LeftBottomSum; } } // 求取情况3的右半部分 RightBottomSum = 0; MaxRightBottomSum = array[mid+1]; for(int i = mid+1;i<=right;i++) { RightBottomSum += array[i]; if (RightBottomSum > MaxRightBottomSum) { MaxRightBottomSum = RightBottomSum; } } // 情况一、情况二 LeftSum = FindFromLCR(array, left, mid); RightSum = FindFromLCR(array, mid+1, right); // 取三种情况的最大值返回 return GetMax(LeftSum, RightSum, MaxLeftBottomSum+MaxRightBottomSum); } // 求三个整数的最大值 int GetMax(int a, int b, int c) { int ans = 0; if (a > b){ ans = a; } else { ans = b; } if (c > ans){ ans = c; } return ans; }};
阅读全文
0 0
- 《剑指offer》——连续子数组的最大和
- 剑指offer——连续子数组的最大和
- 剑指Offer——连续子数组的最大和
- 剑指offer——连续子数组的最大和
- 剑指offer——连续子数组的最大和
- 剑指Offer——连续子数组的最大和
- 剑指offer—连续子数组的最大和
- 剑指offer(30)—连续子数组的最大和
- [剑指offer]连续子数组最大和
- 剑指offer-最大连续子数组和
- 剑指offer:连续子数组最大和
- 剑指offer---连续子数组最大和
- 【剑指offer】连续子数组最大和
- 【剑指offer】5.2时间效率——面试题31:连续子数组的最大和
- 剑指offer代码解析——面试题31连续子数组的最大和
- 【剑指 offer】(31)—— 连续子数组的最大和(动态规划)
- 剑指Offer:面试题31——连续子数组的最大和(java实现)
- 剑指offer——面试题31:连续子数组的最大和
- bootstrap文件上传插件
- 欢迎使用CSDN-markdown编辑器
- 挑战 LCA 学习以及个人理解
- 动态代理
- JavaScript简单验证码
- 剑指offer——连续子数组的最大和
- SFTP
- logs-dir文件日志记录, npm工具包,
- Emnedded Motion Driver 5.1.1 Tutorial中的一些翻译
- HDU5616 Jam's balance[背包dp变形]
- Android IPC机制 Binder学习
- 树莓派之I2C编程
- 使用原生js动态生成Select,根据前面的Select的option生成二级Select
- Tomcat 结构图级比喻