2014年3月4日

摘要: 题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18。分析:当加上一个正数时,和会增加;当加上一个负数时,和会减少。如果当前得到的和是个负数,那么这个和在接下来的累加中应该抛弃并重新清零,不然的话这个负数将会减少接下来的和。基于这样的思路,可以写出如下代码。/*This is the template of *.cpp files */#inc 阅读全文
posted @ 2014-03-04 15:26 程序猿猿猿 阅读(279) 评论(0) 推荐(0) 编辑
摘要: 原理:比较数组最前面一个数的大小,小的数拿出来放在新数组中,最后若是某个数组长度很大,就把剩余部分直接放在新数组末尾/*This is the template of *.cpp files */#includeusing namespace std;int *merge(int *a,int la, int *b, int lb){ int i = 0; int j = 0; int k = 0; int *re = new int[la + lb]; while(i < la && j < lb){ if(a[i] < b[j]){ re[k++] = a 阅读全文
posted @ 2014-03-04 10:22 程序猿猿猿 阅读(166) 评论(0) 推荐(0) 编辑

导航