leetcode刷题 总结,记录,备注 53
2015-06-25 22:55
330 查看
leetcode刷题53
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
注意!这个题目与PAT上那个最大子列和有点区别,PAT上那个题是如果都为负数的话,最大和为0,这题并没有这样的提示,所以如果使用跟那题同样的线性时间的算法,需要在逻辑顺序上进行改动,先与最大的max比较,然后再进行与0的比较,进行置0,下面是代码
Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.For example, given the array
[−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray
[4,−1,2,1]has the largest sum =
6.
注意!这个题目与PAT上那个最大子列和有点区别,PAT上那个题是如果都为负数的话,最大和为0,这题并没有这样的提示,所以如果使用跟那题同样的线性时间的算法,需要在逻辑顺序上进行改动,先与最大的max比较,然后再进行与0的比较,进行置0,下面是代码
class Solution { public: int maxSubArray(vector<int>& nums) { int sum = *nums.begin(), cur = 0; vector<int>::iterator it; for (it = nums.begin(); it != nums.end(); ++it) { cur += *it; if (cur > sum) sum = cur; if (cur < 0) cur = 0; } return sum; } };额外要求里有更难的方法,,,暂且搁置。。。
相关文章推荐
- 一个枚举问题的多种解法
- 大二的ending
- 回答自己的提问
- Material设计非得靠Android L吗?看过来,自定View仿elevation效果!
- leetcode 31:Next Permutation 原理剖析
- SQL的主键和外键约束
- 抽象方法不能是static或native或synchroniz
- python mongodb压力测试脚本
- Android应用实例之有道辞典
- LFS相关
- javaScript语法入门
- 使用Delphi Xe8 开发微信功能 -- (三)微信支付商户平台之查询退款详情
- POJ Frogs' Neighborhood havel-hakimi定理 (简单题)
- More Effective C++ 条款2 最好使用C++转型操作符
- [LeetCode][JavaScript]Pow(x, n)
- shell中IFS用法
- 今天第一个项目感觉很难
- 字节对齐
- URL重写
- 第一个程序HelloWorld