StoneWall【★★★★★】
1 /// <summary> 2 /// Solution 3 /// 100/100 4 /// </summary> 5 /// <param name="H"></param> 6 /// <returns></returns> 7 public int solution(int[] H) 8 { 9 int numBlocks = H.Length; 10 bool isDecreasing = false; 11 Stack<int> stack = new Stack<int>(); 12 for (int i = 1; i < H.Length; i++) 13 { 14 if (H[i] == H[i - 1]) 15 { 16 numBlocks--; 17 isDecreasing = false; 18 } 19 else if (H[i] > H[i - 1]) 20 { 21 stack.Push(H[i-1]); 22 isDecreasing = false; 23 } 24 else 25 { 26 isDecreasing = true; 27 } 28 29 if (isDecreasing == true) 30 { 31 while(stack.Count != 0 && H[i] < stack.Peek()) 32 { 33 stack.Pop(); 34 } 35 if (stack.Count != 0 && H[i] == stack.Peek()) 36 { 37 numBlocks--; 38 } 39 } 40 } 41 return numBlocks; 42 }