剑指offer--3题
生活随笔
收集整理的這篇文章主要介紹了
剑指offer--3题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:輸入一個整形數組,數組里有正數也有負數。數組中連續的一個或多個整數組成一個子數組,每個子數組都有一個和。求所有子數組的和的最大值。要求時間復雜度為O(n)。
例如輸入的數組為1, -2, 3, 10, -4, 7, 2, -5,和最大的子數組為3, 10, -4, 7, 2,因此輸出為該子數組的和18。
第一感覺:看到這道題后,我先想的便是列出所有子數組,求取和再在這些和中求取最大值,這肯定是最簡單的了!自己所寫的代碼如下:
#include "stdafx.h" #include <iostream>int SubArraySumMax(int arr[], int len);using namespace std;int main(int argc, char* argv[]) {int arr[] = {1, -2, 3, 10, -4, 7, 2, -5};int summax = SubArraySumMax(arr,8);cout<<summax<<endl;return 0; }int SubArraySumMax(int arr[], int len) {int i,j;int summax = 0;int sum_temp;for(i=0; i<len; i++){if(summax < arr[i])summax = arr[i];sum_temp = arr[i];for(j=i+1; j<len; j++){sum_temp += arr[j];if(sum_temp > summax)summax = sum_temp;}}return summax; }
但是這樣的思路,其時間復雜度為O(n^2),完全不符合題目所要求的O(n)。自己絞盡腦汁也未能想出更好的辦法。。。
在看過標準答案后,驚嘆于思想+代碼的簡單,不過很遺憾,自己并未豁然開朗。
關鍵未明白為什么可以這樣做?根據評論,作者可能使用了所謂“動態規劃”(DP)的方法,這應該是數據結構中的知識,看來自己還是井底之蛙,還要繼續努力!
?
標準答案:
// jianzhioffer3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> //int SubArraySumMax(int arr[], int len); bool FindGreatestSumOfSubArray (int *pData, // an arrayunsigned int nLength, // the length of arrayint &nGreatestSum // the greatest sum of all sub-arrays ); using namespace std;/*int main(int argc, char* argv[]) {int arr[] = {1, -2, 3, 10, -4, 7, 2, -5};int summax = SubArraySumMax(arr,8);cout<<summax<<endl;return 0; }int SubArraySumMax(int arr[], int len) {int i,j;int summax = 0;int sum_temp;for(i=0; i<len; i++){if(summax < arr[i])summax = arr[i];sum_temp = arr[i];for(j=i+1; j<len; j++){sum_temp += arr[j];if(sum_temp > summax)summax = sum_temp;}}return summax; }*/int main() {int arr[] = {1, -2, 3, 10, -4, 7, 2, -5};int nLength = 8;int nGreatestSum;bool IfSuccess = FindGreatestSumOfSubArray(arr,nLength,nGreatestSum);if(IfSuccess)cout<<nGreatestSum<<endl;elsecout<<"Input Error!"<<endl;return 0; }///// // Find the greatest sum of all sub-arrays // Return value: if the input is valid, return true, otherwise return false ///// bool FindGreatestSumOfSubArray (int *pData, // an arrayunsigned int nLength, // the length of arrayint &nGreatestSum // the greatest sum of all sub-arrays ) {// if the input is invalid, return falseif((pData == NULL) || (nLength == 0))return false;int nCurSum = nGreatestSum = 0;for(unsigned int i = 0; i < nLength; ++i){nCurSum += pData[i];// if the current sum is negative, discard itif(nCurSum < 0)nCurSum = 0;// if a greater sum is found, update the greatest sumif(nCurSum > nGreatestSum)nGreatestSum = nCurSum;}// if all data are negative, find the greatest element in the arrayif(nGreatestSum == 0){nGreatestSum = pData[0];for(unsigned int i = 1; i < nLength; ++i){if(pData[i] > nGreatestSum)nGreatestSum = pData[i];}}return true; }
PS:理解DP后,再來解決它!
轉載于:https://www.cnblogs.com/hello-yz/p/3197508.html
總結
以上是生活随笔為你收集整理的剑指offer--3题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对讲机多少钱啊?
- 下一篇: java动态加载配置文件