Trapping Rain Water—LeetCode(2015/4/8腾讯基础研究线上笔试题)

来源:互联网 发布:大数据工程师培训 编辑:程序博客网 时间:2024/06/15 02:10

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.


The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

1、双指针,一次遍历

int trap(int A[], int n) {        if(n<=2) return 0;        int low=0;        int high=n-1;                int waterSum=0;        int indexMin=0;                while(low<high)        {            while(A[low]<=indexMin&&low<high)            {                waterSum+=(indexMin-A[low]);                low++;            }            while(A[high]<=indexMin&&low<high)            {                waterSum+=(indexMin-A[high]);                high--;            }            indexMin=A[low]>=A[high]?A[high]:A[low];        }        return waterSum;    }

2、可以先找到序列中的最大值,再从两端向中间遍历,此时时间复杂度为O(2n);


0 0
原创粉丝点击