This problem is more difficult to do, at first I think is a stack of solution, feel too cumbersome (out of the stack, into the stack, calculate volume), but it is not a good attempt, this method is still a little problem, after will think clearly. Read the online prompt to complete the final method, this method two times to iterate through the array, the first traversal to find the largest element to the right of each element, the second traversal to find the largest element on the left side of each element, while calculating the index can store the water volume: Min{lefthighest, Righthighest }-a[i]
The final method:
1 Public classSolution {2 Public intTrapint[] A) {3 intlength = a.length, sum = 0, min = 0;4 int[] Lefthighest =New int[length];5 int[] Righthighest =New int[length];6 7 for(intI=length-1; i>=0; i--) {8 if(i = = Length-1) {9Righthighest[i] = 0;Ten } One Else if(A[i+1] > righthighest[i+1]) { ARighthighest[i] = a[i+1]; - } - Else if(A[i+1] <= righthighest[i+1]) { theRighthighest[i] = righthighest[i+1]; - } - } - + for(intj=0; j<length; J + +) { - if(j==0) { +LEFTHIGHEST[J] = 0; A } at Else if(A[j-1] > Lefthighest[j-1]) { -LEFTHIGHEST[J] = a[j-1]; - } - Else if(A[j-1] <= lefthighest[j-1]) { -LEFTHIGHEST[J] = lefthighest[j-1]; - } inMin =math.min (Lefthighest[j], righthighest[j]); - if(Min > A[j]) {//can store water toSum + = min-A[j]; + } - } the returnsum; * } $}
The previous method of using stack to solve is more complex, but it is a good point of thinking:
1 Public classSolution {2 Public intTrapint[] A) {3stack<integer> s =NewStack<integer>();4 inti = 0, sum = 0, Lastpop = 0;5 while(I <a.length) {6 if(S.empty ()) {7 S.push (i);8i++;9 Continue;Ten } One if(A[s.peek ()] < A[i]) {//can hold water if stack contains other elements A while(A[s.peek ()] <A[i]) { -Lastpop =A[s.pop ()]; - if(S.empty ()) { the S.push (i); -i++; - Continue; - } +Sum + = (I-s.peek ()-1) * (A[s.peek ())-lastpop); - } + if(A[s.peek ()] >A[i]) { ASum + = (I-s.peek ()-1) * (A[i]-lastpop); at S.push (i); -i++; - Continue; - } - if(A[s.peek ()] = =A[i]) { -Sum + = (I-s.peek ()-1) * (A[i]-lastpop); in S.pop (); -i++; to Continue; + } - } the Else if(S.peek () = =A[i]) { *i++; $ Continue;Panax Notoginseng } - Else if(S.peek () >A[i]) { the S.push (i); +i++; A Continue; the } + } - returnsum; $ } $}