接雨水-算法题
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ #define MAX 12 //lintcode water area question int main(int argc, char** argv) { //build water and black area int a[MAX]={0,1,0,2,1,0,1,3,2,1,2,1}; int maxNumber=0; int maxNumberPos=0; int rootNode=0; int areaWater=0; for(int i=0;i<12;i++) { if (a[i]>maxNumber) { maxNumber=a[i]; maxNumberPos=i; } } //find max number and postion printf("%d,Pos:%d\n",maxNumber,maxNumberPos); rootNode=a[0];//auto rootNode value for(int i=0;i<maxNumberPos;i++) { if (rootNode<a[i]) rootNode=a[i]; else areaWater +=(rootNode-a[i]); } printf("Result areaWater: %d\n",areaWater); rootNode=a[MAX-1];//auto rootNode value for(int i=MAX-1;i>maxNumberPos;i--) { if (rootNode<a[i]) rootNode=a[i]; else areaWater +=(rootNode-a[i]); } printf("Result areaWater: %d\n",areaWater); system("pause"); return 0; } //for next code
两个指针夹逼的办法实现
复杂度O(n)空间复杂度O(1)
时隔2年没有编写C code 手写一遍算法 没报错
posted on 2015-07-16 18:40 winters1992x 阅读(342) 评论(0) 编辑 收藏 举报