Trapping Rain Water
生活随笔
收集整理的這篇文章主要介紹了
Trapping Rain Water
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目如下:
Given?n?non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,?
Given?[0,1,0,2,1,0,1,3,2,1,2,1], return?6.
解析思路:先找到最高峰,然后從兩邊向中間計算,因為兩邊向中間是遞增的趨勢
參考代碼如下:
int trap(int A[], int n) {if(n <= 2) return 0;int max = -1, maxInd = 0;int i = 0;for(; i < n; ++i){//先找出最高峰if(A[i] > max){max = A[i];maxInd = i;}}int area = 0, root = A[0];for(i = 0; i < maxInd; ++i){//從左側(cè)到最高峰的計算if(root < A[i]) root = A[i];else area += (root - A[i]);}for(i = n-1, root = A[n-1]; i > maxInd; --i){//從右側(cè)到最高峰的計算if(root < A[i]) root = A[i];else area += (root - A[i]);}return area;}總結(jié)
以上是生活随笔為你收集整理的Trapping Rain Water的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《剑指offer》反转链表
- 下一篇: 《剑指offer》合并两个排序的链表